Reputation: 1556
There is a piece of code which is producing error of "Lvalue required". The code is as,
#include<stdio.h>
#include<conio.h>
#define max 10
int main()
{
printf("%d",max++);
return 0;
}
It was evident that Lvalue error will come in above code so i changed the code to
int a;
printf("%d",a=max++);
I thought now the value of constant is assigned to a proper variable but still the error appeared. Then i checked for
printf("%d",a=max+1);
it works without any error.What is the problem with the second piece of code ?
Upvotes: 5
Views: 285
Reputation: 123478
Remember that the ++
operator has a side effect of updating the value of its operand; for that to work, the operand must be an lvalue, which is an expression that refers to a memory location such that the memory may be read or modified; unfortunately, no memory is set aside for integer constants like 10
, hence the error message.
Upvotes: 0
Reputation: 234715
max
is a literal so max++
will fail. (Just as 10++
will fail).
However, max + 1
is valid (just as 10 + 1
is).
Remember that #define
s are resolved by the preprocessor which happens before compilation takes place.
To explain your compiler's return error:
Loosely speaking, an lValue is the thing on the left hand side of an assignment; i.e. in
a = b;
a
is the lValue. The statement 10 = b;
is clearly meaningless (you can't assign a value to 10): more formally it is invalid since 10 is not an lValue.
Upvotes: 5
Reputation: 47794
max
will be replaced by 10 after preprocessing, so
max++ => 10++ //Error ++ requires lvalue
a=max++ => a=10++ //Error same as above
a=max+1 => a=10+1 //Works
Upvotes: 2
Reputation: 7225
max is replace by 10 after c preprocessing, which is what #define
supposed to do.
10 is a rvalue, or literal. No assignment related operation should do to a literal. But ++
operation involves assignment.
For example, you can do 10++;
for the literal 10.
Upvotes: 2
Reputation: 2851
You need to read about compiler macro definitions.
What they actually do is if you type:
#define SOMETHING 3
is changing every occurrence of something with the further value before compiling the code.
Similar if you use such macro:
#define SOMETHING(x) (x + x)
It will change the occurrence of SOMETHING(value) to value + value.
The LValue is basically the operand that can be used in the left site of assign operator, in your case it can be a "a" variable.
The value++ is translated to the operation value = value + 1 and wouldn't cause any problems if the variable had been used. You, however had used "max" which is not a variable of any type but its a macro defined from your preprocessor as constant variable. The preprocessor will swap each max to 10 so you end up with the expression 10++ which will evaluate to 10 = 10 + 1 which is just wrong.
Note: you should use defines with capital leather to easier distinguish between variables and preprocessor definitions.
Upvotes: 2