can prefix and post be used at the same time on a variable in c
#include <stdio.h>
int main()
{
char *q;
char *p = "sweta";
q = ++p++;
printf("%s", q);开发者_StackOverflow社区
}
what is the output is this program valid as it gives an error of l value required.
q = ++p++;
this won't even compile in C or in C++
Post increment operator has higher precedence than pre increment operator
So q= ++p++
is interpreted as q = ++(p++)
. Now the post increment operator returns an rvalue
expression whereas the preincrement operator requires its operand to be an lvalue
.
ISO C99 (Section 6.5.3.1/1)
Constraints
The operand of the prefix increment or decrement operator shall have qualified or unqualified real or pointer type and shall be a modifiable lvalue.
This can't be done, as you can't increment a temporary object.
You can't use prefix/postfix operators more than one time on a variable. This is because the operator returns a copy of the original variable, so using another operator on the copy would not change the original variable. C/C++ do not allow this to prevent confusion.
If you want to increment the variable by two while copying the new value to q
, you can use q=(p+=2);
instead of q=++p++;
Don't try too clever and push the language where it is not supposed to go. It will bite you someday. Or bite your customer and they will bite you.
Just be sane and code it this way:
#include <stdio.h>
int main()
{
char* q;
char* p = "sweta";
q = p++;
q = ++p;
printf("%s\n", q);
}
which gives me this:
eta
精彩评论