tags:

views:

104

answers:

4
#include <stdio.h> 

int main()
{
    char *q;
    char *p = "sweta";
    q = ++p++;
    printf("%s", q);
}

what is the output is this program valid as it gives an error of l value required.

+3  A: 

This can't be done, as you can't increment a temporary object.

Clark Gaebel
+1  A: 

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++;

Dumb Guy
that wouldn't follow the original intent, as it would (supposedly) pre-increment, assign, then post-increment.
Scott M.
Then use `q=(p+=2)-1;`
R..
+10  A: 

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.

Prasoon Saurav
Unless, of course, you overload `operator++`: for instance, it's perfectly legal, given `std::vector<T> v`, to say `*++v.begin()` to get the second element. Not sure why you would, but I suppose there's a situation for everything.
Jon Purdy
The question has been tagged C.
Prasoon Saurav
+1  A: 

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
C Johnson