int main(void)
{
int i = 10, j =20;
j = i, j ? (i, j) ? i : j : j;
printf("%d %d", i, j);
return 0;
}
What is the output?
Please somebody guide me how to interpret the nested ternary operator in this case.
C is defined by a language grammar; a precedence table is a handy condensing of the grammar into something that humans can take in at a glance, but it doesn't exactly correspond to what the grammar specifies.
You may need to consult the language grammar in order to resolve associativity around a ternary operator. Personally I always explicitly use parentheses so that a reader who's not a language lawyer can still understand what's going on (and so that I don't make mistakes).
An example is:
c ? c = a : c = b
which must be parsed as
(c ? c = a : c) = b
which is illegal in C, since the ternary operator does not give an lvalue. Incidentally, the C++ grammar is different; in that language this is parsed as
c ? c = a : (c = b)
which is legal; and also the ternary operator can give an lvalue in C++.
In your case, the question is which of the following it is:
Z = ((i , j) ? X : Y)
Z = (i , (j ? X : Y))
(Z = i, j) ? X : Y
(Z = i), (j ? X : Y)
I believe the latter is correct here, so you should end up with j = i plus an expression with no side-effect.
What you have here is hopefully code you have read and you want to get rid of, not code you actually use.
You have a combination of two unparenthesed ternay operators and two uses of the comma operator.
Despite no use of parentheses, the nesting of ?: is unambiguous:
a ? b ? c : d : e
can only mean
a ? ( b ? c : d) : e
as there is no other way to interpret it.
The 2nd comma operator is in parentheses, so it is unambiguous as well.
The only point of doubt is the comma operator at the start, where you might want to consult a precedence table.
Here we see that , has the lowest precedence and thus we have
(j = i), (j ? (i, j) ? i : j : j);
which is a comma operator with an assignment as first expression and an unevaluated other expression as second expression, which is the result.
In short, if we omit the right side, which isn't used nevertheless, we just have j = i, but this expression lacks unreadability.
So the output is 10 10.
Great trap, this expression... but as it is written, the answer doesn't cover this. If I erroneously evaluated it as j = j ? i : j; I would get 10 10 as well.
Related
#include <stdio.h>
#define max(x,y)(x)>(y)?x:y
int main() {
int i = 10;
int j = 5;
int k = 0;
k == max(i++, ++j);
printf("%d%d%d ", i, j, k);
return 0;
}
I know the answer. It is 11 7 0 but how? please help me with the execution of the ternary operator.
The statement
k==max(i++,++j);
is expanded to
k==(i++)>(j++)?i++:j++;
Note that == has higher precedence than ?: operator and therefore the above expression is equivalent to
( k == ((i++)>(j++)) )?i++:j++;
Since (i++)>(j++) will be true, therefore k == ((i++)>(j++)) is evaluated as false and hence j++ (and it's value become 7) will be evaluated (i++ will be skipped).
NOTE: The above expression does not invoke undefined behavior because there exists sequence point between the evaluation of the first operand of the ternary operator and the second or third operand. For example, the expression
a = (*p++) ? (*p++) : 0
has well defined behavior.
This question is definitely a trick question that will catch many unsuspecting C programmers. The different responders here have more than 100 years of compounded experience in C, yet it took several tries to get this right:
The expression k == max(i++, ++j); expands to:
k == (i++)>(++j)?i++:++j;
Which is parsed as this (== has lower precedence than >, but higher precedence than ?):
(k == ((i++) > (++j)))
? i++
: ++j;
The ternary operator evaluates the test (i++)>(++j), which is true for the values in the program, hence evaluates to 1, different from the value of k, so it proceeds to evaluate the third expression j++, which increments j a second time and returns the intermediary value 6. There is a sequence point between the test and the branch that is executed, so it is OK to increment j twice. The second branch is not executed at all since the test evaluated to false.
i is incremented once, its value becomes 11.
j is incremented twice, its value is 7.
k is not modified by the above statement, because == is the comparison operator, not the assignment operator.
Hence the output is 11 7 0
Notes:
The program uses a macro max that evaluates its arguments more than once and they are not properly parenthesized in the expansion: 2 errors that illustrate the shortcomings of macros. This macro should be names MAX to emphasize the fact that its arguments should not have side effects and its expansion should be fully parenthesized this way:
#define MAX(x,y) ((x) > (y) ? (x) : (y))
A better alternative is to make it an inline function:
static inline int max(int x, int y) {
return x > y ? x : y;
}
If the program had this statement:
k = max(i++, ++j);
The output would be 12 6 11 because unlike ==, = has lower precedence than ? so the statement would expand to:
k = ((i++) > (++j))
? i++
: ++j;
You can study the table of operator precedence for C. There are in my humble opinion too many levels and it is very difficult to memorize all of them, especially since some of them are rather counter-intuitive: print a copy and keep it handy or make a bookmark. When in doubt, use parentheses.
You're using a double equal sign, which is a comparison. k==max(i++,++j); compares the return value of max to k, which is 0.
Instead, try changing the == to =.
It is known that both assignment = and conditional ?: operators have right associativity. In following code sample:
#include <stdio.h>
int main(void)
{
int a, b, c, d;
a = b = c = d = 1;
1 ? a++ : b ? c++ : d;
printf("%d %d %d %d\n", a, b, c, d);
return 0;
}
the assignment:
a = b = c = d = 1;
is equivalent to:
a = (b = (c = (d = 1)));
and correspondingly:
1 ? a++ : b ? c++ : d;
is the same as:
1 ? a++ : (b ? c++ : d);
What the Standard say about this last case? Does it guarantee that such combined expression is evaluated from left to right (so the c++ part is not evaluated), just as opposite to assignment?
The evaluation order of ?: is guaranteed: the first operand is evaluated first, then evaluate the second or the third operand depending on whether the first operand is true.
You are mainly confused about the relationship between operator precedence/associativity and order of evaluation. They play different roles. The former decides how operators are grouped, while the latter decides which sub-expression is evaluated first.
Consider the expression a * b + c * d, the precedence rule means it's equivalent to (a * b) + (c * d). But is it guaranteed that the compiler will evaluate a * b before c * d? The answer is no, in this example, the operator + doesn't guarantee the order of evaluation.
The conditional operator ?: is one of the few operators that do have a specified order of evaluation. (The rest are &&, ||, and ,).
In your example
1 ? a++ : b ? c++ : d;
1 ? a++ : (b ? c++ : d);
are always equivalent, in both expressions, 1 is evaluated first, and since it's true, a++ is evaluated next, the end.
Associativity and precedence do not define order of evaluation. These concepts are completely unrelated. Order of evaluation in C is defined by sequencing rules, not by precedence or associativity.
It is true that a = b = c = d = 1; is associated as a = (b = (c = (d = 1)));, but that does not mean that d = 1 should be evaluated first, especially in C language, where assignment operator evaluates to an rvalue.
Associtivity simply says that c should receive value 1 converted to the type of d ("as if" it was read from d). But that does not mean that d = 1 should be done first. In your example all variables have the same type, which means that the whole thing is equivalent to a = 1; b = 1; c = 1; d = 1; in absolutely any order. There's no sequencing inside a = b = c = d = 1 expression.
The same logic applies to ?: operator. Its associativity simply tells you which operand belongs to which operator. And the grouping is indeed 1 ? a++ : (b ? c++ : d);. But associativity does not tell you anything about the order of evaluation. Order of evaluation in ?: operator is defined separately and independently: the condition is always evaluated (sequenced) first, then one (and only one) of the branches is evaluated. In your example 1 is evaluated first, then a++ is evaluated and its result becomes the result of the entire expression. The (b ? c++ : d) part is not even touched.
1 ? a++ : b ? c++ : d;
is equivalent to
if (1) {
a++;
}
else {
if (b) {
c++;
}
else {
d;
}
}
So, the output will be
2 1 1 1
This question already has answers here:
Errors using ternary operator in c
(5 answers)
Closed 8 years ago.
(k < m ? k++ : m = k)
This particular expression gives compile time error saying lvalue required. The problem is with k++. Not able to understand what is wrong in this expression.
The input
k < m ? k++ : m = k;
is parsed as
((k < m) ? k++ : m) = k;
where k++ is an rvalue and m is an lvalue. So the conditional is an rvalue.
You probably mean something like
(k < m) ? k++ : (m = k);
Better use
if (k < m) {
k++;
} else {
m = k;
}
instead.
You can see the C precedence table e.g. here: http://en.cppreference.com/w/c/language/operator_precedence.
The terms "lvalue" and "rvalue" mostly mean "things that you can write left of an assignment" and "things you can only write on the right side of an assignment", resp. C.f. "Are literal strings and function return values lvalues or rvalues?".
An easier example to see the semantics of ?:: For a uint8_t k, what does condition ? k : k + 1 mean?
Easy to see the former part k is an lvalue with the type uint8_t.
The latter expression k + 1 is somewhat trickier, though. Being the result of an arithmetic expression, it is an rvalue. Also it's not a uint_8 but int.
The common type of uint8_t and int is int. So in total condition ? k : k + 1 is an rvalue expression with the type int.
Can anybody please tell me why this statement is giving an error - Lvalue Required
(a>b?g=a:g=b);
but this one is correct
(a>b?g=a:(g=b));
where a , b and g are integer variables , and a and b are taken as input from keyboard.
In the expression,
(a > b ? g = a : g = b);
the relational operator > has the highest precedence, so a > b is grouped as an operand. The conditional-expression operator ? : has the next-highest precedence. Its first operand is a>b, and its second operand is g = a. However, the last operand of the conditional-expression operator is considered to be g rather than g = b, since this occurrence of g binds more closely to the conditional-expression operator than it does to the assignment operator. A syntax error occurs because = b does not have a left-hand operand (l-value).
You should use parentheses to prevent errors of this kind and produce more readable code which has been done in your second statement
(a > b ? g = a : (g = b));
in which last operand g = b of : ? has an l-value g and thats why it is correct.
Alternatively you can do
g = a > b ? a : b
The expression:
(a>b?g=a:g=b)
parsed as:
(a>b?g=a:g)=b
And we can't assign to an expression so its l-value error.
Read: Conditional operator differences between C and C++ Charles Bailey's answer:
Grammar for ?: is as follows:
conditional-expression:
logical-OR-expression
logical-OR-expression ? expression : conditional-expression
This means that a ? b : c = d parses as (a ? b : c) = d even though (due to the 'not an l-value' rule) this can't result in a valid expression.
One side note:
Please keep space in you expression so that it become readable for example.
(a>b?g=a:g=b);
Should be written as:
(a > b? g = a: g = b);
similarly, you should add space after ; and ,.
The problem is operator precedence: In C the ternary conditional operator (?:) has a higher precedence than the assignment operator (=).
Without parenthesis (which don't do anything here) your expression would be this:
a > b ? g = a : g = b;
The operator with the highest precedence in there would be the comparison >, so this is where you'll get your first logical grouping:
(a > b) ? g = a : g = b;
The next highest expression is the ternary conditional, which results in the following expression:
((a > b) ? (g = a) : (g)) = b;
As you can see, you'll now end up with an lvalue (i.e. a value; not a variable) on the left side of your assignment operator, something that won't work.
As you already noticed, the solution to this is to simply group the expressions on your own. I'd even consider this good practice, especially if you're unsure how your precedence might play out. If you don't want to think about it, add parenthesis. Just keep code readability in mind, so if you can, resolve the operator precedence on your own, to ensure you've got everything right and readable.
As for readability: I'd probably use a classic if() here or move the assignment operator outside the ternary conditional, which is how you usually define max():
g = a > b ? a : b;
Or more general as a macro or inline function:
#define max(a, b) ((a) > (b) ? (a) : (b))
inline int max(int a, int b) {
return a > b ? a : b;
}
if(a>b)
{
g = a;
}
else
{
g = b;
}
that can be replaced with this
g = a > b ? a : b; //if a>b use the first (a) else use the second (b)
Your expression (a>b?g=a:g=b) is parsed as :
(a>b?g=a:g)=b
// ^^^
From the Microsoft documentation :
conditional-expression:
logical-or-expression
logical-or-expression ? expression : conditional-expression
In C, the operator ?: has an higher precedence that the operator =. Then it means that ( a ? b : c = d ) will be parsed as ( a ? b : c ) = d. Due to l-value's rule, the first expression is also valid but is not doing what you think.
To avoid this error, you can do also :
g = ( a > b ) ? a : b;
This question usually triggers a barrage of answers trying to explain the situation through the concept of operator precedence. In reality it cannot be explained that way, since this is a typical example of an input, on which surrogate concepts like "operator precedence" break down. As you probably know, there's really no "operator precedence" in C. There are only grammatical groupings, which generally cannot be expressed precisely through any linear ordering of operators.
Let's take a look at what the language specification says about it. The relevant portions of C grammar in this case are the grammars of ?: operator and = operator. For ?: operator it is
conditional-expression:
logical-OR-expression
logical-OR-expression ? expression : conditional-expression
and for the = operator it is
assignment-expression:
conditional-expression
unary-expression assignment-operator assignment-expression
In the first case the critical part is the last operand of ?: operator: it is not an expression, but rather a conditional-expression. The conditional-expression is a different entry point into the grammar of C expression: it "enters" the grammar at the point where it is no longer possible to include a top-level = operator into a conditional-expression. The only way to "smuggle" a = operator into a conditional-expression is to descend the grammar all the way to the very bottom
primary-expression:
identifier
constant
string-literal
( expression )
generic-selection
and then wrap around all the way to the top using the ( expression ) branch. This means that a conditional-expression can contain a = operator only when it is explicitly wrapped in (...). E.g. the grammar prohibits you from having g = b as the last operand of ?: operator. If you want something like that, you have to explicitly parenthesize it: <smth> ? <smth> : (g = b).
A very similar situation exists with the second piece of grammar: assignment operator. The left-hand side (LHS) of assignment is unary-expression. And unary-expression "enters" the general grammar of C expression at the point where it is too late to include a top level ?: operator. The only way to reach the ?: operator from unary-expression is to descend all the way down to primary-expression and take the ( expression ) branch. This means that grammar prohibits you from having a > b ? g = a : g as the LHS operand of = operator. If you want something like that, you have to explicitly parentesize it: (a > b ? g = a : g) = <smth>.
For this reason "popular" answers claiming that "operator precedence" makes the language to parse your expression as
(a > b ? g = a : g) = b
are actually completely incorrect. In reality, there's no derivation tree in formal C grammar that would make your input fit the syntax of C language. Your input is not parsable at all. It is not an expression. It is simply syntactically invalid. C language sees it as a syntactic gibberish.
Now, in practice you might see some implementations to respond with a "lvalue required as left operand of assignment" diagnostic message. Formally, this is a misleading diagnostic message. Since the above input does not satisfy the grammar of C language expression, there's no "assignment" in it, there's no "left operand" and there's no meaningful "lvalue" requirement.
Why do compilers issue this strange message? Most likely they do indeed parse this input as a valid C expression
(a > b ? g = a : g) = b
The result of ?: is never an lvalue in C, hence the error. However, this interpretation of your input is non-standard (extended?) behavior, which has no basis in formal C language. This behavior of specific implementations might be caused by their attempts to reconcile C and C++ grammars (which are quite different in this area), by their attempts to produce a more readable (albeit "fake") error message or by some other reason.
Typically, in such implementations a similar issue also would pop up in case of inputs like
a + b = 5
The same error would be issued, suggesting a (a + b) = 5 parse, while from the pedantic point of view a + b = 5 is not parsable as an expression at all (for the same reasons as described above).
Again, formally, this is not enough to say that the compiler is "broken": the compiler is required to detect a constraint violation and issue some diagnostic message, which is exactly what happens here. The fact that the text of the diagnostic message does not correctly reflect the nature of the problem is inconsequential (the compiler can simply say "Ha ha ha!"). But one undesirable consequence of such misleading diagnostics is that it misleads users into misinterpreting the problem, which is BTW painfully evident from the barrage of formally incorrect answers posted to this question.
This question already has answers here:
Is a += b more efficient than a = a + b in C?
(7 answers)
Closed 9 years ago.
what is the difference between i = i + j; and i += j; in C?
Are they equivalent? Is there any side effect of i?
I was trying to check the assignment mechanism in C using the GCC compiler.
They're almost the same. The only difference is that i is only evaluated once in the += case versus twice in the other case.
There is almost no difference, but if i is a complex expression, it is only computed once. Suppose you had:
int ia[] = {1, 2, 3, 4, 5};
int *pi = &(ia[0]); // Yes, I know. I could just have written pi = ia;
*pi++ += 10;
// ia now is {11, 2, 3, 4, 5}.
// pi now points to ia[1].
// Note this would be undefined behavior:
*pi++ = *pi++ + 10;
i = i + j is equivalent to i += j but not same.
In some cases(rare) i += j differs from i = i + j because i itself has a side effect.
Also one more problem is operator precedence i.e
i = i * j + k;
is not same as
i *= j + k;
The two statements i = i + j and i += j, are functionally same, in first case you are using the general assignment operation, while the second one uses the combinatorial assignment operator. += is additive assignment operator (addition followed by assignment).
The use of combinatorial assignment operators generates smaller source code that is less susceptible to maintenance errors and also possibly a smaller object code where it would also run faster. Compilation is also likely to be a little faster.
Syntactic sugar baby.
Any differences are just going to come down to compiler implementation.
http://en.wikipedia.org/wiki/Syntactic_sugar
In both cases i (the variable or expression being assigned) must be an lvalue. In most simple cases this will yield code that is identical in both cases so long as i is not declared volatile.
However there are a few cases where a lvalue can be an expression involving operators, and this may cause evaluation of i twice. The most plausible example of an lvalue expression that might be used in that way is perhaps simple dereferencing of a pointer (*p):
*p = *p + j ;
*p += j ;
may generate different code, but it is trivially optimised so I would expect not even without optimisation enabled. Again p cannot be volatile, otherwise the expressions are semantically different.
A less plausible scenario is to use a conditional operator expression as an lvalue. For example the following adds j to b or c depending on a:
(a ? b : c) += j ;
(a ? b : c) = (a ? b : c) + j ;
These might generate different code - the compiler might reasonably not spot that idiom and apply an optimisation. If the expression a has side effects - for example were the expression getchar() == '\n' or a is volatile (regardless of b or c), then they are not equivalent since the second would evaluate to:
c = b + j for the input "Y\n",
b = b + j for input "\n\n",
c = c + j for input "YN".
These points are of course mostly irrelevant - if you write code like that and it does things you did not expect, sympathy may be in short supply!