Reputation: 5857
I've created this simple program to auto-generate sequence of frames to be used in Avisynth scipt:
#include <stdio.h>
int main(void) {
const int step = 3;
const int arr[] = {31997, 31998, 32001};
int i, ii = 0;
for(i = 32002; i <= 32121; i += step, (sizeof(arr)/sizeof(int) - 1 ) != ii ? ++ii : ii = 0) {
printf("freezeframe(%d,%d,%d)\n", i, i + step, arr[ii]);
}
return 0;
}
Using MinGW with GCC 4.6.2, I get this error: lvalue required as left operand of assignment.
The issue is simply solved by using parenthesis around ii=0. However, I don't get why it is an error. Shouldn't the assignment operator be evaluated first?
Upvotes: 0
Views: 180
Reputation: 46533
It is always advised to use parenthesis, if you write your code in this fashion
(sizeof(arr)/sizeof(int) - 1 ) != ii ? ++ii : ii = 0
like
(((sizeof(arr)/sizeof(int) - 1 ) != ii ? ++ii : ii) = 0)
9 out of 10 times you will stuck.
So make a habit of putting parenthesis and this doesn't make any overhead on the compilers!!!
Upvotes: 0
Reputation: 53017
Wikepedia has a short section which explains this: http://en.wikipedia.org/wiki/Operators_in_C_and_C++#Notes
The grammar for conditional operator in C is
logical-OR-expression ? expression : conditional-expression
Note that an assignment-expression
is not considered a conditional-expression
, and a conditional expression cannot be the left of an assignment expression and so it's technically a syntax error. See the grammar: http://www.lysator.liu.se/c/ANSI-C-grammar-y.html
However, GCC is (incorrectly) parsing it as:
((sizeof(arr)/sizeof(int) - 1 ) != ii ? ++ii : ii) = 0
Which is a semantic error since ++i
is not an lvalue expression.
Upvotes: 3
Reputation: 145829
The conditional operator has higher precedence than the assignment operator in C.
(sizeof(arr)/sizeof(int) - 1 ) != ii ? ++ii : ii = 0
is evaluated as
((sizeof(arr)/sizeof(int) - 1 ) != ii ? ++ii : ii) = 0
For a quick reminder of the operators precedence in C, you can see this:
http://www.kernel.org/doc/man-pages/online/pages/man7/operator.7.html
Upvotes: 4