How to define and use global and local variable with the same name in C

1 Answer

0 votes
#include <stdio.h>

void function1(void);
void function2(void);

int n; // global

int main(int argc, char **argv) 
{ 
    n = 0;
    printf("main() n = %d\n", n); // 0
    
    function1();
    printf("main() n = %d\n", n); // 0 // local variable didn't change global variable
 
    function2();
    printf("main() n = %d\n", n); // 12345
    
    n = 77;
    printf("main() n = %d\n", n); // 77
    
    n = 999; // this value (999) will NOT change to 100 in function1
             // it's a different variable (the global) with the same name
    function1();
    printf("main() n = %d\n", n); // 999 
    
    return(0);
}

void function1(void)
{
   int n = 100; // local
   
   printf("finction1() n = %d\n", n); // 100
}

void function2(void)
{
   n = 12345; // global
}

/*
run:

main() n = 0
finction1() n = 100
main() n = 0
main() n = 12345
main() n = 77
finction1() n = 100
main() n = 999

*/

 



answered Jun 12, 2015 by avibootz

Related questions

2 answers 171 views
1 answer 205 views
205 views asked Jun 12, 2015 by avibootz
3 answers 323 views
2 answers 282 views
282 views asked Jun 13, 2015 by avibootz
...