Reputation: 36111
Disclaimer: I'm not writing code like this, I know it's ugly and unreadable.
I'm generating C, and I need everything to be in one expression.
This works:
#define true 1
int a = (true) ? ( (true) ? (puts("a"), puts("b"), 1) : (2) ) : (3);
printf("%d\n", a);
a
b
1
But I also need to have statements, not just expressions. This fails to compile:
int a = (true) ? ( (true) ? (puts("a"), puts("b"), (if (true) puts("c");), 1) : (2) ) : (3);
error: expected expression
Is it impossible to achieve in C?
Upvotes: 2
Views: 74
Reputation: 134336
Using the gcc extension, you can wrap around the statements in braces, like
int a = (true) ? ( (true) ? (puts("a"), puts("b"), ({if (true) puts("c");}), 1) : (2) ) : (3);
Upvotes: 4
Reputation: 198324
You cannot have statements inside an expression, no. However, as you noted, you can have boolean operators and the ternary operator.
if (true) puts("c");
can be written in an expression like
true ? puts("c") : false
or
true && puts("c")
Upvotes: 3