PDA

View Full Version : C++ problem


Wilbert
12th September 2004, 17:54
I'm making a filter which contains the following simplified code


if (lstrcmpi("pal", "pal") == 0) {int stand_width = 0;}

stand_width = stand_width + 1;

stand_width should be 1, but the compiler keeps complaining "error C2065: 'stand_width' : undeclared identifier" :confused:

dragongodz
12th September 2004, 18:26
you have put the initialisation in a condition. if that condition is not met then it isnt declared and then you are still trying to use it. move the declaration outside like this.

int stand_width;

if (lstrcmpi("pal", "pal") == 0) {stand_width = 0;}

stand_width++;

Wilbert
12th September 2004, 19:21
Thanks! (I thought it didn't matter because the condition is always met, but I guess that's not important.)

Manao
12th September 2004, 20:09
The compilator can't know that the condition is always met. It is only known when the code is executed. Anyway, in C++, a variable declared inside brackets ( or whatever '{}' are called ) is only valid in those brackets.

Richard Berg
13th September 2004, 06:21
if(1)
{
/* stuff */
int foo;
/* stuff */
}

foo = 0;


In some cases the compiler can determine that a conditional is always true and will write assembly language for "stuff" without any branches. However, the last line is still not legal C++ code, so the parser will error out.

avih
13th September 2004, 08:55
it doesn't matter whether the CC is always met or not. what matters is that the braces define a compund statement (C.S.) and a new scope, that contains the declaration and definition the the variable stand_width. therefore, its scope is ONLY within that C.S. block.

i.e. this code will also fail to compile:

.
.
{
int var_in_inner_scope=1;
} // from here onwards, var_in_inner_scope isn't recognized anymore. ceased to exist, as it's scope terminated.
int a=var_in_inner_scope; // fail compilation due to undeclared identifier (for this scope)
.
.


you must use a variable in the same (or contained) scope in which you defined it. if you go out of scope, you can't use that var anymore, as it won't compile.

this would work however:

.
.
int var_in_outer_scope; //usually initializing vars is always preffered. i skipped it for the sake of the example.
{
var_in_outer_scope=1; // works as expected, and modifies the previously defined var in a containing block.
}
int a=var_in_outer_scope; //works well since it's beeing used on the same scopt it was defined
.
.



cheers ;)
avih

dragongodz
13th September 2004, 09:19
ok guys i think Wilbert no doubt gets it by now. any more and this will belong in the devlopment section. :D