Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does c = ++(a+b) give compilation error?

Tags:

c

increment

After researching, I read that the increment operator requires the operand to have a modifiable data object: https://en.wikipedia.org/wiki/Increment_and_decrement_operators.

From this I guess that it gives compilation error because (a+b) is a temporary integer and so is not modifiable.

Is this understanding correct? This was my first time trying to research a problem so if there was something I should have looked for please advise.

like image 245
dng Avatar asked Jun 20 '18 14:06

dng


People also ask

Why do compilation errors occur?

Compilation error refers to a state when a compiler fails to compile a piece of computer program source code, either due to errors in the code, or, more unusually, due to errors in the compiler itself. A compilation error message often helps programmers debugging the source code.

Which of the following has compilation error in C?

Hence, the correct answer is "#include<stdio.

Will ++ i ++ give compilation error?

No, it give an error.


2 Answers

It's just a rule, that's all, and is possibly there to (1) make it easier to write C compilers and (2) nobody has convinced the C standards committee to relax it.

Informally speaking you can only write ++foo if foo can appear on the left hand side of an assignment expression like foo = bar. Since you can't write a + b = bar, you can't write ++(a + b) either.

There's no real reason why a + b couldn't yield a temporary on which ++ can operate, and the result of that is the value of the expression ++(a + b).

like image 173
Bathsheba Avatar answered Sep 29 '22 23:09

Bathsheba


The C11 standard states in section 6.5.3.1

The operand of the prefix increment or decrement operator shall have atomic, qualified, or unqualified real or pointer type, and shall be a modifiable lvalue

And "modifiable lvalue" is described in section 6.3.2.1 subsection 1

An lvalue is an expression (with an object type other than void) that potentially designates an object; if an lvalue does not designate an object when it is evaluated, the behavior is undefined. When an object is said to have a particular type, the type is specified by the lvalue used to designate the object. A modifiable lvalue is an lvalue that does not have array type, does not have an incomplete type, does not have a const-qualified type, and if it is a structure or union, does not have any member (including, recursively, any member or element of all contained aggregates or unions) with a const-qualified type.

So (a+b) is not a modifiable lvalue and is therefore not eligible for the prefix increment operator.

like image 25
Christian Gibbons Avatar answered Sep 29 '22 23:09

Christian Gibbons