943,947 Members | Top Members by Rank

Ad:
  • C++ Discussion Thread
  • Unsolved
  • Views: 1896
  • C++ RSS
Sep 17th, 2004
0

problem about statement

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

PLS EXPLAIN ME.
Similar Threads
Reputation Points: 11
Solved Threads: 0
Light Poster
Sukhbir is offline Offline
31 posts
since Jul 2004
Sep 17th, 2004
0

Re: problem about statement

Quote originally posted by Sukhbir ...
C++ Syntax (Toggle Plain Text)
  1. char *ptr="abc";
  2. char *ptr1;
  3. while(*ptr1++=*ptr++); //IT IS WORKING
  4. while((*ptr1)++=(*ptr)++); //ERROR
PLS EXPLAIN ME.
[Added [code][/code].]

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.
Team Colleague
Reputation Points: 2780
Solved Threads: 312
long time no c
Dave Sinkula is offline Offline
4,790 posts
since Apr 2004
Sep 17th, 2004
0

Re: problem about statement

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.
Reputation Points: 36
Solved Threads: 11
Posting Pro in Training
Chainsaw is offline Offline
436 posts
since Jun 2004

This thread is more than three months old

No one has posted to this discussion for at least three months. Please let old threads die and do not reply to them unless you feel you have something new and valuable to contribute that absolutely must be added to make the discussion complete. Otherwise, please start a new thread in this forum instead.
Message:
Previous Thread in C++ Forum Timeline: 128bit arithmetic
Next Thread in C++ Forum Timeline: Need Help counting Array Length





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC