Search code examples
cgotoconditional-operator

ternary operator and goto in c, executing both


I'm trying to implement goto in ternary operator:

So here is what I'm doing :

(a<5 && done==0) ? ({goto dd;}) : ({goto ee;});

With those braces I'm trying to convert statement into expression.

The problem is, both labels are being executed. Why?

Here's the code (Ideone link):

#include<stdio.h>
int main()
{
    int a=0,sum=0;
    int done=0;

    (a<5 && done==0) ? ({goto dd;}) : ({goto ee;});

    dd:
        printf("%d - %d -- %d\n",a,sum,done);
        ++a,sum+=a;
    ee:
        printf("done\n");
        done=1;
    return 0;
}

Solution

  • After goto dd;, program control jumps to the dd label, executes the statements there, and continues to the statements following the ee label. To make control not flow from the statements after the dd label to the statements after the ee label, you must insert a return statement or other jump statement.

    ({goto dd;}) is a terrible abuse of the GCC statement-expression extension. Do not use that code.