Doesn't it look strange

Recommended Posts

long x; char *ptr; *((long *)ptr)++; //shouldn't this be wrong?

Share on other sites
all pointers to POD types are the same size.
so, the cast to a long* is fine.
the increment will work as long as there is 4bytes of data stored at the location ptr points to.
The results may be undefined/not what you expect, but it is still valid code.

Share on other sites
Why should it be wrong? That code alone will almost certainly cause a runtime error (a crash most likely, assuming you're not running it in a debugger), but why would it cause a compile time error (I assume that's what you mean by "wrong")?

Share on other sites
Isn't that cast equivalent to an assignment to an unnamed temporary variable of the given type. If the postincrement were to do anything, it would have to increment that unnamed temporary, so the change would be lost forever.

Share on other sites
Quote:
 Original post by JapaneseIsn't that cast equivalent to an assignment to an unnamed temporary variable of the given type.

No, but that would require casting. Casting is converting from one type to another.

Quote:
 If the postincrement were to do anything, it would have to increment that unnamed temporary, so the change would be lost forever.

As I said, it does not work that way. It simply changes the type of that part of the expression.

Share on other sites
The last line of that code is similiar to what I used to do in the scanline renderer of my software 3D engine:
char *currPixel;...*((long*)currPixel)++ = val;
It is equivalent to:
char *currPixel;...long *temp = (long*)currPixel;*temp = val;currPixel += sizeof(long);

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

• Partner Spotlight

• Forum Statistics

• Total Topics
627681
• Total Posts
2978611

• 13
• 12
• 10
• 12
• 22