0

char *ptr="abc";
char *ptr1;
while(*ptr1++=*ptr++); //IT IS WORKING
while((*ptr1)++=(*ptr)++); //ERROR

PLS EXPLAIN ME.

3
Contributors
2
Replies
3
Views
13 Years
Discussion Span
Last Post by Chainsaw
0

char *ptr="abc";

char *ptr1;

while(*ptr1++=*ptr++); //IT IS WORKING

while((*ptr1)++=(*ptr)++); //ERROR[/code]PLS EXPLAIN ME.

You haven't initialized ptr1 : when you first dereference it, it is already undefined behavior, so "IT IS WORKING" is just plain "luck(?)".

In the "ERROR" line, the result of the ++ operator is not an lvalue, so it cannot be assigned to.

Edited by diafol: fixed formatting

0

Sukhbir, you have a lot of interesting syntax questions, and they are all covered in one chapter of any good C book, because these questions all revolve around the way the C compiler (and thus the C++ compiler) has been specified to work. You can also go into the help for your compiler and look for 'precedence'; there is a nice table that lists the exact order specified by the language.

In your first example,

*ptr1++

is the same as

*(ptr1++)

to the compiler, thus your second example, where you supplied the parens, would be different. In general, when writing code like this that might confuse someone, it is nice to put in the parens explicitly, even if they are not strictly needed by the compiler.

Dave's comments are also right on.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.