Why does the above code doesnot give a variable redifinition error..Although the variable i is defined outside of block also??Code:#include<stdio.h> int i=5; main() { int i=6; { int i=7; printf("%d",i); } printf("%d",i); }
Why does the above code doesnot give a variable redifinition error..Although the variable i is defined outside of block also??Code:#include<stdio.h> int i=5; main() { int i=6; { int i=7; printf("%d",i); } printf("%d",i); }
That's just the way the language was designed.
The three i's are in distinct scopes. They are not redefinitions of each other.
It's not illegal to do such things, but it can lead to occasional confusion.
Hence this optional warning from GCC
Code:$ gcc -Wall -Wshadow foo.c foo.c:3:1: warning: return type defaults to ‘int’ [-Wreturn-type] foo.c: In function ‘main’: foo.c:5:9: warning: declaration of ‘i’ shadows a global declaration [-Wshadow] foo.c:2:6: warning: shadowed declaration is here [-Wshadow] foo.c:8:13: warning: declaration of ‘i’ shadows a previous local [-Wshadow] foo.c:5:9: warning: shadowed declaration is here [-Wshadow] foo.c:13:1: warning: control reaches end of non-void function [-Wreturn-type]
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
If at first you don't succeed, try writing your phone number on the exam paper.