Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

goto line of code failing to execute

Tags:

c++

c

goto

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?

like image 421
finiteloop Avatar asked Oct 22 '10 20:10

finiteloop


People also ask

What is the biggest problem with GOTO statement?

"The GOTO statement is generally considered to be a poor programming practice that leads to unwieldy programs. Its use should be avoided."

What can I use instead of goto?

Alternatives to the “goto” are “break” and “continue”.

What is goto statement in C?

The goto statement allows us to transfer control of the program to the specified label .


1 Answers

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).

like image 88
SoapBox Avatar answered Oct 06 '22 10:10

SoapBox