145x Filetype PDF File size 0.25 MB Source: inc.kmutt.ac.th
INC 161 , CPE 100
Computer Programming
Lecture 10
Scope of Variables
Global and Local Variables
Although it is not recommended, global variables shared by different
functions can be used to communicate between functions.
The same identifiers can be used in different scopes. The values of the
variables are stored in different memory locations.
Example global /* File: global.c */
#include
int g = 10; // global variable
Output: void func1(void) { Global variable
g++;
printf("g in func1() = %d\n", g);
g in func1() = 11 }
g in func2() = 12 void func2(void) {
g in func3() = 1 g++;
g in main() = 12 printf("g in func2() = %d\n", g);
}
void func3(void) {
int g=0; // local variable
g is the same g++;
is all functions printf("g in func3() = %d\n", g);
because it is a }
main() {
global variable func1();
func2();
func3();
printf("g in main() = %d\n", g);
}
Example local /* File: local.c */
#include
Output: void func1(void) {
int g = 1; //try removing this line later
g++;
printf("g in func1() = %d\n", g);
}
main() {
int g = 1;
printf("g in main before func1() = %d\n", g);
g is different func1();
printf("g in main after func1() = %d\n", g);
when it is in }
different {..} pair
g in main before func1() = 1
g in func1() = 2
g in main after func1() = 1
no reviews yet
Please Login to review.