Monday, December 27, 2010

Will this code compile ?

#define X 8;
int main(void)
{
 ++X; // will this line compile?
}
The concept of lvalues and rvalues must be explained a bit in order to really understand this problem. Before we proceed, you should note that the definition of lvalues and rvalues presented here is not exact as even the C Standards themselves are rather vague on the definition.

An object is a region of memory that can be examined, but not necessarily modified. An lvalue is an expression that refers to such an object. The term lvalue originally referred to objects that appear on the left (hence the 'l') hand side of an expression. That definition no longer applies since any const-qualified type is also considered to be an lvalue, but it can never appear on the left hand side of an assignment statement because it can not be modified. So, the term "modifiable lvalue" was created to refer to an lvalue that can be modified, and a const-qualified type does not fall into this category. 

An rvalue is any expression that has a value, but cannot have a value assigned to it. One could also say that an rvalue is any expression that is not an lvalue . An example of an rvalue would be a literal constant - something like '8', or '3.14'. 

Now let's try to solve the problem. Strictly speaking, the operand of the prefix (or postfix) increment operator must be a non-modifiable lvalue. Now that we know what an lvalue is, we must ask ourselves if X is an lvalue. X is a macro, which means that it does not identify a place in memory - macros use simple text replacement via the preprocessor. Because macros don't exist in a region of memory, they are not lvalues. This means that X can not be used as an operand of the prefix increment operator. Thus, the code shown above will not compile.
 

No comments:

Post a Comment