A global variable is a variable declared outside all functions. Its scope extends from its declaration to the end of the program, its memory allocation too. A global variable permanently allocates the memory space intended for it.
Prefer local variables and parameter passed to functions instead of global variables.
If within a function a variable coexists with a global variable of the same name, it is the local variable that is considered in the function.
Here is an example of a program that uses a global variable:
int i=0; // Global variable i
void fct(void);
int main(void) {
for ( ;i<5;i++) // The loop uses i
fct ();
return 0;
}
void fct(void) {
printf ("i= %d\n", i); // The function also uses i
}
The variable i
is a global variable that is readable and writable in the main()
and in the fct()
function.
The following program is provided which contains 4 global variables. Correct the program to remove all global variables by replacing them with local variables and functions arguments.
# include <stdio.h>
// Global variables TO BE DELETED
int a,b,c,sum;
// Function that ask for an integer
void input (void);
int main(void)
{
// Ask the first integer
input();
a=c;
// Ask the second integer
input();
b=c;
// Display the sum
sum=a+b;
printf ("The sum is %d\n",sum);
return 0 ;
}
// Function that ask for an integer
void input (void)
{
printf ("Enter an integer: ");
scanf ("%d",&c);
}
Global variables are...
The scope of a global variable is ...
The memory allocated for a global variable ...
What does the following program display?
#include <stdio.h>
int var = 7;
int main(void) {
int var = 12;
printf ("var = %d",var);
return 0;
}
var
: a local and a global. Local variables overwrite global variables.
Try again...