Thursday, November 24, 2011

Learn C programming tutorial lesson 8 - Functions


Functions are sub-programs. You have already been using a function which is the main function.
You must always declare a function before the function that calls it. The main function will be calling our function so we will put ours above main.
First put its return value such as int or char. If you don't want a return value then use void. After that give it a unique name and put a set of brackets after that. You then put the set of curly brackets which will have the sub-program between them. We will call our function Hello because it will simply print the word Hello on the screen.
#include

void Hello()
{
   printf("Hello\n");


}

int main()
{
   Hello();
   return 0;
}

Parameters

Parameters are values that are given to a function so that it can perform calculations with them. The "Hello\n" which we used in the Hello function is a parameter which has been passed to the printf function.
You need to declare variables inside the parameter brackets to store the values of the parameters that are passed to the function. Here is an Add function which adds the 2 parameters together and then returns the result.
#include

int Add(int a,int b)
{
   return a + b;
}

int main()
{
   int answer;
   answer = Add(5,7);
   return 0;
}

You can pass the address of a variable to a function so that a copy isn't made. For this you need a pointer.
#include

int Add(int *a,int *b)
{
   return *a + *b;
}

int main()
{
   int answer;
   int num1 = 5;
   int num2 = 7;
   answer = Add(&num1,&num2);
   printf("%d\n",answer);
   return 0;
}

Global and local variables

A local variable is one that is declared inside a function and can only be used by that function. If you declare a variable outside all functions then it is a global variable and can be used by all functions in a program.
#include

// Global variables
int a;
int b;

int Add()
{
   return a + b;
}

int main()
{
   int answer; // Local variable
   a = 5;
   b = 7;
   answer = Add();
   printf("%d\n",answer);
   return 0;
}

Command-line parameters

Sometimes you also pass parameters from the command-line to your program. Here is an example:
$ myprogram -A
To be able to access the command line parameters you have to declare variables for them in the brackets of the main function. The first parameter is the number of arguements passed. The name of the program also counts as a parameter and is parameter 0. The second parameter is the arguements in a string array.
#include

int main(int argc,char *argv[])
{
   int i;
   printf("Amount: %d\n",argc);
   if (argc > 0)
   {
      printf("Parameters:\n");
      for (i = 0;i < argc;i++)
         printf("%s\n",argv[i]);
   }
   return 0;
}

0 comments:

Post a Comment

Setec Institute || Group : SH6 | | Name : Kim Chanthy. Powered by Blogger.

 
Design by Free WordPress Themes | Bloggerized by Lasantha - Premium Blogger Themes | Hot Sonakshi Sinha, Car Price in India