C Programming: How to Use Variables in Functions

By Dan Gookin

In C programming, functions that use variables must declare those variables — just like the main() function does. In fact, it’s pretty much the same thing. The big difference, which you need to remember, is that variables declared and used within a function are local to that function. Or, to put it in the vernacular, what happens in a function stays within the function.

LOCAL VARIABLES IN A FUNCTION

#include <stdio.h>
void vegas(void);
int main()
{
 int a;
 a = 365;
 printf("In the main function, a=%dn",a);
 vegas();
 printf("In the main function, a=%dn",a);
 return(0);
}
void vegas(void)
{
 int a;
 a = -10;
 printf("In the vegas function, a=%dn",a);
}

Both the main() and vegas() functions declare an int variable a. The variable is assigned the value 365 in main() at Line 9. In the vegas() function, variable a is assigned the value -10 at Line 20. Can you predict the program’s output for the printf() function on Line 12?

Exercise 1: Create a new project using the source code from Local Variables in a Function. Build and run.

Here’s the outpute:

In the main function, a=365
In the vegas function, a=-10
In the main function, a=365

Even though the same variable name is used in both functions, it holds a different value. That’s because variables in C are local to their functions: One function cannot change the value of a variable in another function, even if both variables sport the same type and name.

  • The general admonition about not duplicating variable names doesn’t hold for variables in other functions. You could have 16 functions in your code, and each function uses the alpha variable. That’s perfectly okay. Even so:

  • You don’t have to use the same variable names in all functions. The vegas() function from Listing 10-3 could have declared its variable as pip or wambooli.

  • To allow multiple functions to share a variable, you specify a global variable.