0

I'm a little bit confused about why the below compiles. I've tried looking into some resources to explain it (Kernighan's The C Programming Language) but to no avail. My confusion arises from why the last part of the compound declaration works. My understanding is that the "int" at the start of the line applies to every subsequent variable (hence why they are all initialized as ints). If this is so, then why is it not illegal to redefine nmax which has global scope?

int  nmax  =  20; 
/* The  main()  function  */ 
int  main ( int  argc ,  char  ** argv ){  // entry  point 
   int a = 0, b = 1, c, n, nmax = 25;  
   printf ( "%3d: %d\n",1 ,a );  
   printf ( "%3d: %d\n",2 ,b ); 
   for  (n  = 3;  n <=  nmax;  n++)  { 
      c = a + b;  a = b;  b = c;  
      printf ( "%3d: %d\n",n, c ); 
   } 
}
EE18
  • 109
  • 1
  • 1
    I don't see any compound declaration here. Anyway, local variables are allowed to *shadow* the global ones. – Eugene Sh. Dec 10 '19 at 20:03
  • Hi @EugeneSh., thanks very much for pointing me in the right direction. "Shadow" is exactly what I was looking for, I didn't know what to look up previously. Quick question for you then. The nmax declared in main() here is then **different** than the global nmax, right? And were we to want to change that global nmax to 25, we could either simply write (in main() ) nmax = 25; on another line, or extern nmax = 25; on the same line? Or would the latter not work because then we have effectively written int extern nmax = 25; which is the wrong order for int and extern? – EE18 Dec 10 '19 at 20:10
  • Check this out: https://stackoverflow.com/questions/618769/how-can-i-access-a-shadowed-global-variable-in-c – Eugene Sh. Dec 10 '19 at 20:11
  • Thanks for the reference. It would seem then that the answers to my above questions are all yes. Thanks again! – EE18 Dec 10 '19 at 20:13

0 Answers0