Question

Somebody write this function

void strToUpper(char *p) {
  while (*p) {
    *p = TOUPPER(*p);
    *p++;                //<-- Line to pay attention
  }
}

I asked, why do you put the * before p++?

answer: because "It's the same", I corrected the code and then stay angry for a while, because both really work the same...

void strToUpper(char *p) {
  while (*p) {
    *p = TOUPPER(*p);
    p++;                //<-- Line to pay attention
  }
}

So I would like to share this with stackoverflow, example:

char s[6]="hello";

What would it do?

*++ptr;

This will evaluate the ++ pre-increment(over the pointer) and then the dereference operator *, so it will let a char value 'e' (second letter of "hello") (that is not used in this case and could generate a warning on compilation) and the pointer will be pointing from the 'e' (position 1)

What would it do?

*ptr++;

This is a little weird because it will evaluate the dereference operator * first, so it will let a char value 'h' (that is neither used in this case), and then the ++ post-increment(to the pointer), so (again) the pointer will be pointing from the 'e' (position 1)

What would it do?

ptr++;

Finally it won't have a Lvalue of char, but it won't generate any warning if isn't used, and the pointer will be pointing from the 'e' (position 1) too.

These three forms does the same from the pointer address point of view..

IMHO That's the worst thing of some computer languages (almost everyone)..

"There is a poor Hamming distance between any code and any bug"

We have no redundancy when programming, if you take a Law book, and write random chars within, It will be readable, but if you type random when programming, you get a bug, 100% accuracy

Was it helpful?

Solution

++ has precedence over *. But I agree, it's unclear when you mix both in the same statement.

OTHER TIPS

According to the operator precedence in C, ++ will evaluate first, and only then *. So in *p++, ptr will get its value inceremented, and then the statement will get the value of the opbject to which ptr is now pointing to. Of course, this isn't different from ptr++, since you aren't using the value of the statement.

Anyone who mixes ++, --, += etc with other operators has already failed writing readable code, the fact that they'll bug it out is nothing more than their due.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top