Maifee Ul Asad
Maifee Ul Asad

Reputation: 4607

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;
}

Upvotes: 0

Views: 578

Answers (2)

Saurabh Panthri
Saurabh Panthri

Reputation: 44

Ternary operator returns a value. It does not execute the statement. Hence your goto's are not getting executed.

Upvotes: -1

Eric Postpischil
Eric Postpischil

Reputation: 222650

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.

Upvotes: 7

Related Questions