Pointer Problem

rezaxyz's Avatar, Join Date: Jun 2010
Newbie Member
Hi all,

I've seen below code for sending a string to output device:

void displayText(uint8_t *p)
{
while(*p !='\0')writeData(*(p++));
}

from "C Operator Precedence" table I found that "++" operator is higher than "*" but why writeData function sends current character and after that increment p ?

Thank in advance,
Reza
0
cfsantos's Avatar, Join Date: Jun 2010
Newbie Member
Change "p++" for "++p"

Your code means "Write p data and after increment p". This change that I told you means "increment p and after write p data".

I hope I could help.

Claudio
0
xpi0t0s's Avatar, Join Date: Aug 2004
Mentor
Because that's what the post-increment operator means. p++ means take the value of p THEN increment it, and the timing of the increment is compiler dependent but will always be after the value of p is taken. So if p is 5, then p++ evalues to 5 and p then contains 6.

So WriteData(*(p++)) means: take the value of p, dereference it, call WriteData with what it found. At some point p will be incremented.

In Visual Studio this is equivalent to WriteData(*p); p++; and all side effects are treated the same way, so if you had something silly like printf("%d %d %d", i++, i++, i++); and i is 5 to start with, then this would display "5 5 5" then increment i 3 times. The reason this is silly in a real application is that the behaviour depends on the exact timing of the postincrement; it could be valid for another compiler to display 5 6 7, or 7 6 5, depending on the order of evaluation and the exact timing of the ++. But this is a useful way to find out how your compiler handles side effect operators.