Functions in C Programming – Part 4

In the last tutorial I told you about the passing values to the functions. I hope you had read that tutorial at least twice till now. So today I will tell you about some typical nuances of using functions in C language. I will also tell you about the scope rule of functions. So lets start with our first objective


Rules for using functions in C

1. The variables that are passed by main() function are called actual arguments or parameters and the variables in which the user defined function receives those values is called formal arguments or parameters.

2. We can pass any number of actual arguments. But it should be in the same number and order to the formal arguments.

3. We can also use the same variable name for both formal and actual arguments but the compiler will treat them different.

4. Compiler automatically passes the control to the calling function when it encounters the closing brace of user defined function. There is no need for some return statement for it.

5. However if you want to return some value to the calling function then you should use return statement for it.

6. You can use any number of return statements in your program. There is no restriction for that.

7. Some variations while using return statement

return(b);
return(4); 
return(2.67);
return;

Last return statement will return any garbage value to the calling function. And we can drop the parenthesis in that case.

8. We can only return one value at a time. It’s a restriction in C. So below statements will not work.

return(x, y);
return(6,4);

9. IMPORTANT – When we change the value of formal arguments then those values will not change in actual arguments.

E.g. Suppose we pass two variables to some function. And in that function I received the values in that variables in some local variable. So when we change the values of those local variables the it will not affect to the values of actual variables.

Scope Rule of Functions

In this rule I will tell you about the reason behind point number 9 in above rules. Till now you must be asking that why we should pass the values to some function explicitly?

The simple reason is that the default scope of variables inside some functions is local to it. It means the variables inside main() function can only be accessed in main() function. We cannot access them in any other function. So that is why we have to pass values to the user defined functions explicitly. 

Leave a Comment

Your email address will not be published. Required fields are marked *