Basic Structure of a Function in C

I write this article assuming that you have some experience with programming at least in one programming language (easy for me :P). If any of you can’t understand what’s a compiler or other programming basics used here, but wants to proceed with C, you can request (comment here) and I can explain.

void main (void)               // the main function
{
The body…
}

Explanation

The word “main” is the function name. In C every program should have at least one function and it should be the main function. When you compile the program with the use of a compiler, it looks for the main function first.

After the syntax “void main (void)” you open braces and write the function body. Here you will declare variables, change the status of microcontroller pins, etc (everything you did with assembly language is possible here).

Talking about the body, every statement in it should end with a semiclone(;). As you can remember in Assembly language the semiclone was used to let the compiler know that we are writing a comment till the line ends. But this is different in C and some other languages. You can put a single line comment using “//” or multi line comment with “/*” and “*/”. Also the number of braces you open in a function should be closed before the end of the program. Spaces separates keywords. Additional tabs are not required. But tabs will improve clarity.

When you call a function you can give an input if you want. Then in the end of the function you can get an output corresponding to the input (again only if you want). For example if your function is f(x) = x+2 and if you input x=1 the output will be 3. Or you can just make the function do something (like changing the status of microcontroller pins) without any input value and output value from the function.

The keyword “void” at the beginning is the return type. This can be any type you want (int, double).”void” stands for no return type. “int” stands for integer. Assume the body doesn’t return any value. So the keyword “void” must be used.

The keyword “void” in the parentheses is the Argument type. You don’t give any input to the main function usually. Afterall its the main function and it starts running first, so how its going to receive any input. Therefore the keyword void is used as the argument type.

Except for the main function, for the functions you define, you have to put the function prototype on top of the code. The Function prototype will be discussed later.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: