I came across this problem. The question was: Will this code compile successfully or will it return an error?
#include <stdio.h>
int main(void)
{
int first = 10;
int second = 20;
int third = 30;
{
int third = second - first;
printf("%d\n", third);
}
printf("%d\n", third);
return 0;
}
I personally think that this code should give an error as we are re initializing the variable third in the main function whereas the answer to this problem was that this code will run successfully with output 10 and 30.
Then I compiled this code on VS Code and it gave an error but on some online compilers it ran successfully with no errors, can somebody please explain?
I don't think there can be two variables with the same name inside the curly braces inside main. If third was initialized after the curly braces instead before it would work completely fine. Like this:
#include <stdio.h>
int main(void)
{
int first = 10;
int second = 20;
{
int third = second - first;
printf("%d\n", third);
}
int third = 30;
printf("%d\n", third);
return 0;
}
Your posted programs are defining the following 4 distinct
intvariables:first.second.thirdin the outer scope.thirdin the inner scope.Variables #3 and #4 are distinct, despite both variables having the same name. When using the identifier
thirdin the inner scope, you are referring to variable #4. When using that identifier in the outer scope, you are referring to variable #3.There can, and there indeed are. This is not good programming style, but the language allows you to do this.
If you want the compiler to emit a warning when one variable's name shadows another variable's name, then, with the compilers gcc and clang, you can compile with the
-Wshadowcommand-line option.Since your posted code is valid C code, it should not give an error message, only maybe a warning message (unless you tell the compiler that you want to treat warnings as errors).
You cannot access the variable in the outer scope from the inner scope directly. However, you can still access that variable from the inner scope indirectly, via a pointer:
This will print: