Unsolved Compilator missing errors...
-
...or am I wrong here? Having code:
int method(char c) { int i = -1; if(c == char(0xa7)) { int i = static_cast<int>(c) + 1; } else { i = -2; } return i; }
notice redeclaration of the
i
var.
Is this legit? Cause it goes through compilation w/o errors but because of this code gives wrong results. -
Which "i" var do you mean? The one at the beginning of the method or the other one which exists only inside the if-block and gets lost at the end of the "if".
-
So it is valid code?
There is no redeclaring here?
I thought thati
exists inmethod
"scope" so sinceif
is insidemethod
thei
already exist in this "scope" so there should be notification about redeclaration of variable. -
Hi,
Your
if
body is a new scope that will end at the closing curly brace, so technically nothing wrong with re-declaring a variable with the same name except it makes your code confusing and won't give you the result you expect.You might get a shadowing warning though.
-
@SGaist Shadowing warning? I know this warning (with gcc) only, when a parameter of a method gets hidden by some local variable in the code. Well, other compiler may print out different warnings.
With this example the compiler finds something, that might not be what you (the thread starter) really want …
g++ -W -Wall -Wextra -c example.cpp example.cpp: In function ‘int method(char)’: example.cpp:6:10: warning: unused variable ‘i’ [-Wunused-variable] int i = static_cast<int>(c) + 1; ^
In general it is a good idea to turn on all warnings, read those warnings and try to understand them.
-
@Wurgl, that's why I used "might" ;)
In any case, I agree with you, all warnings on is a good habit.