I've tried to find this online, but all the other questions are about code that is nothing related to what I'm looking for. I'm trying to see if I can have multiple executing lines in a ternary operator:
#include <stdio.h>
int main()
{
int i == 1;
i = 1?{printf("H");printf("J")}:printf("H");
}
The output of this is the error:
Error: expected expression before ‘{’ token
What is wrong here to cause that?
CodePudding user response:
I'm trying to see if I can have multiple executing lines in a ternary operator
You can, using a comma operator
i = 1?printf("H"),printf("J"):printf("H");
CodePudding user response:
This error message is telling you that no, you can't have multiple executing lines in a ternary operator.
This is because the {}
and all statements inside constitute a block, but not an expression. This is because, roughly speaking, the block, unlike an expression, does not have a value, and the ternary operator itself cannot output a value if one its branches doesn't have one. Consider: what value would a
contain after the following?
auto a = 1 ? { printf("H"); printf("J") } : printf("H");
The ternary operator syntax has the form expression1 ? expression2: expression3
.
CodePudding user response:
you can replace your line with:
printf(i==1? "HJ" : "H");