Reputation: 433
When I tried to assign a pointer in switch statement, the
compile gave me an error warning, but when I debugged the code by declaring
the pointer outside the switch statement. The code
syntactically passed. Why? Can anyone explain it to me? Thank you!
Before I debugged:
void Left_Balance(treeNode **T)
{
treeNode *p=(*T)->left;
switch(p->bf)
{
case LH:
p->bf=(*T)->bf=EQ;
L_Rotate(T);
break;
case RH:
treeNode *q = p->right;
switch(q->bf)
{
case LH:
(*T)->bf=RH;
p->bf=EQ;
break;
case EQ:
(*T)->bf=q->bf=EQ;
break;
case RH:
p->bf=LH;
(*T)=EQ;
break;
}
q->bf=EQ;
R_Rotate(&p);
L_Rotate(T);
break;
}
}
After I debugged :
void Left_Balance(treeNode **T)
{
treeNode *p=(*T)->left;
treeNode *q; //Here is the difference
switch(p->bf)
{
case LH:
p->bf=(*T)->bf=EQ;
L_Rotate(T);
break;
case RH:
q = p->right; //Here is the difference
switch(q->bf)
{
case LH:
(*T)->bf=RH;
p->bf=EQ;
break;
case EQ:
(*T)->bf=q->bf=EQ;
break;
case RH:
p->bf=LH;
(*T)=EQ;
break;
}
q->bf=EQ;
R_Rotate(&p);
L_Rotate(T);
break;
}
}
Upvotes: 0
Views: 67
Reputation: 225344
case RH:
treeNode *q = p->right;
Here you have a label right before a declaration. A label can only come before a statement. You can fix this by adding an empty statement right before the declaration that the label can be associated with:
case RH:
;
treeNode *q = p->right;
Upvotes: 0
Reputation: 32596
in your first version treeNode *q = p->right;
is not in a block ({}
)
an other possibility was to add that block
case RH:
{
treeNode *q = p->right;
switch(q->bf)
{
case LH:
(*T)->bf=RH;
p->bf=EQ;
break;
case EQ:
(*T)->bf=q->bf=EQ;
break;
case RH:
p->bf=LH;
(*T)=EQ;
break;
}
q->bf=EQ;
R_Rotate(&p);
L_Rotate(T);
break;
}
Warning
(*T)=EQ;
is very suspicious because *T
is a treeNode *
and EQ is not one because of case EQ
Probably you want
(*T)->bf = EQ;
(edit)
As @dbush indicates it is enough to add a statement between the label and the declaration, but to not put the declaration in a block is very dangerous, look at that code :
#include <stdio.h>
int main(int argc, char ** argv)
{
switch (argc) {
case 1:
puts("case 1");
int i = 123;
puts("i initialized and continue in case 2");
case 2:
printf("in case2, i values : %d\n", i);
}
return 0;
}
What about i used in printf if the program is called with an argument initializing argc is 2 ?
Note gcc accepts that code but not g++ without the option -fpermissive
and with that option the code is compiled without case 2:
This is why I proposed to add a block.
Upvotes: 1