Intel Interview Question
Software Engineer / DevelopersCountry: United States
Interview Type: Phone Interview
There are a lot of correct answers below about pre-increment and post-increment.
If this were the actual interview question, I would clarify with the interviewer if i or a have been initialized. If the above snippet is all that is provided, then the compiler will complain on both about un-initialized variables, and be unable to perform operations.
On the other side, if the variables are initialized, you will get a different kind of error for both. The pre/post increment causes that side of the expression to be a value not a variable. The compiler cannot assign the value of a to another value. It will have to assign it to a variable.
i++ increments the variable but returns its value before the increment.
++i increments the variable and returns a reference to the variable.
the = operator needs a L-value on the left side to be able to assign the value of a to i. the first statement does not return an L-value, while the second statement does (return variable i).
sup i=10, a=3;
->: ++i = a
-> : (i=i+1)=a //highest priority operator ++ other than = ,because first execute the left side statement
-> : i=11=a //here variable 'a' require left value.so,the compiler produced error "L Value required"
*This is same as post and pre increment
(++i)=a is correct
i++=a is incorrect
as ++i can be used as L-value
any pre-increement or pre decreement can be used as L-value
but post-increement cannot be used!
None of them are correct!
Rule :
When executing "x=y", 'x' should be assignable(for example, address where you store)
reason :
(++i) increments value of i and gives you after increment "value of 'i'"
(i++) gives you "value of i" and then increments 'i'.
So in the given problem, (++i) or (i++) always gives you "value" either before increment or after increment, to which you cannot "asssign some other value directly.
gcc gave me "error: lvalue required as left operand of assignment" for both
If you read the C or C++ standard, both would be wrong.
A compiler is more likely to accept ++i, but you should not code this way as it is not strictly allowed in the standards.
both the lines are correct provide some initial value for i... here i++ is a post increment operator where value is assigned first and then incremented.whereas ++i is a pre increment operator where value is incremented and then assigned.
If int i is not initialized then both expression ( assignment to a = (++i) ; and a = (i++) ) are wrong . Compiler Will produce an error related to initialization of integer i.
- shravan40 September 10, 2013