Synfire's Guide To C Programming

6. Functions

Functions allow you to create blocks of code that can be called when needed. This makes programming easier than it was in the old days of carving 1's and 0's into magnetic tape. Back then everytime you wanted to do something in your code you had to input it there, now with the introduction of functions you can create a block code that can be executed just by tying the functions name into your program.

As we touched on in the first chapter, a function is defined with a return type, this return type specifies what kind of data the function will return. Lets have a look at a simple program that incorperates the use of functions, the first one don't return a value, while the second demonstrates a returned value and shows how to pass arguments to the function.

func1.c
#include <stdio.h>

void Say();
/* creates a function without arguments or a return value */

int main()
{
    printf("In main()\n");
    Say(); /* executes the code in Say() */
    printf("Back in main()\n");
    return 0;
}

void Say()
{
    printf("In Say()\n");
}
func2.c
#include <stdio.h>

unsigned float Add(int x, int y);
int main()
{
    int Num1, Num2;
    unsigned float Answer;
    printf("Enter the first number: ");
    scanf("%d", &Num1);
    printf("Enter the second number: ");
    scanf("%d", &Num2);
    Answer = Add(Num1, Num2); /* calls the Add() function
                     and sends Num1 and Num2 as
                     arguments. Then the return
                     value is assigned to Answer. */
    printf("%d + %d = %f\n", Num1, Num2, Answer);
    return 0;
}

unsigned float Add(int x, int y)
{
    return (x+y);
}

Just as you can pass arguments to your functions you must remember main() to is a function. The only difference is that when you pass arguments to main() it is done from the command line.

argc&argv.c
#include <stdio.h>

int main(int argc, char *argv[])
{
    if (argc >= 1)
    {
        printf("Usage: arg [string...]");
        return(1);
    }
    printf("%s", argv);
    return(0);
}
Well that covers the basics of functions, As this isn't by no means a definitive guide, it works for what this text is, a tutorial, not a book.

< < < Lesson 5: Program Control | Lesson 7: Arrays > > >



Want some naughty smileys for your Yahoo messenger? Then look HERE.