Abusing the gnu extensions.

This is an interesting thing I found while fiddling with the gnu extensions, in particular the compound statement expressions. i.e. ({code;})
Here it is:
1
2
3
4
5
6
7
#include "stdio.h"
int main(){
	int y=0,x=0;
	y=({x++; goto b; 1;}),x++;
	b:printf("%d\n",y);
	return 0;
}

1 0

The goto statement in the CSE causes the CSE to not "return". Thus the value of y is 0, but x is 1. Next I'll try jumping between CSEs (didn't work).
Last edited on
It is an interesting question you bring up.

I presume when compiler see the goto b; statement it immediately execute a "jump" out of your CSE and come to b: It seems no assignment of 1 to variable y is done at all.

But since x++ is executed BEFORE goto b; the final x value is 1.

1
2
3
4
      int y=0,x=0;
      y=({x++; goto b; 1;});
      b:printf("%d\n",y);
      printf("%d\n",x); //x value is 1 


If x++ is executed AFTER goto b; the final x value is 0 which is logical since goto b; would have "jump" out without giving x a chance to be incremented.

1
2
3
4
        int y=0,x=0;
        y=({goto b; x++;});
        b:printf("%d\n",y);
        printf("%d\n",x); //x value is 0 
That's what I thought, but it seems that the jump cancels out the entire outside statement:
1
2
3
4
5
6
7
8
#include "stdio.h"
int main(){
	int y=0,x=0;
	y=x++ + ({goto b; 1;});
	b:
	printf("%d %d\n",x,y);
	return 0;
}

0 0
Last edited on
Now something strange happen. If you use ++x you get the value of x as 1.

1
2
3
y=++x + ({goto b; 1;});
b:
printf("%d %d\n",x,y);//here the value of x is 1 


So I guess is for ++x, the increment is done FIRST before attempt to evaluate the + expr. But if x++, the increment is to be done AFTER the whole + expr has finished executing correct ?
Yes. But it never finishes executing, so the increment never happens.
And the moral of the story is avoid goto statements like plague :P

Truly speaking I did not use any goto statement in any of my C/C++ program at all. I uses break and continue but not goto.

Maybe Standard C++ committee should remove goto from the C/C++ language :)
Topic archived. No new replies allowed.