goto line of code failing to execute
I have always been taught to almost never to use goto statements in programming. However we are required to do so as part of my most recent programming project. I have an if/else statement with various goto statements, and the goto statements are failing to execute. I have no idea why. Any help would be appreciated.
int myInt = XXXXXXX;
if((myInt>>22) & 7 == X)
goto a;
else if((myInt>>22) & 7 == Y)
goto b;
开发者_高级运维 else if((myInt>>22) & 7 == Z)
goto c;
a:
printf("this always executes\n");
goto end;
b:
printf("this never executes\n");
goto end;
c:
printf("nor does this\n");
goto end;
end:
//more code
A brief explanation of the bit shifting and such: We are implementing a computer processer, and need to look at the first 3 bits of a 25-bit opcode. So (myInt >> 22) & 7 isolates the 3 bits in the opcode.
Any ideas as to what is going on here?
This actually has nothing to do with goto. You've got an operator precedence problem. Bitwise and (&) has lower precedence than equality (==). As a result, you're actually doing if ((myInt>>22) & (7 == X))
.
To fix it, just add some parens: if ((myInt>>22) & 7) == X)
.
I see that }
that makes me think that labels and corresponding printf
are declared outside a function. Of course you can't do that.. they have to be inside a method anyway.
(it's just a guess, also because I see you've got other problems as other answers state :)
The '==' operator has a higher precedence than '&' in C/C++.
Try if ( ((myInt>>22) & 7) == X)
instead
精彩评论