Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Disclosure: My content contains affiliate links.

43,700 questions

57,013 answers

573 users

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 297 views
1 answer 308 views
308 views asked Jun 12, 2015 by avibootz
3 answers 496 views
2 answers 420 views
420 views asked Jun 13, 2015 by avibootz
...