Go4Expert (http://www.go4expert.com/)
-   C (http://www.go4expert.com/forums/c/)
-   -   Pointer Problem (http://www.go4expert.com/forums/pointer-problem-t22517/)

rezaxyz 24Jun2010 15:18

Pointer Problem
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,

cfsantos 25Jun2010 13:56

Re: Pointer Problem
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.


xpi0t0s 25Jun2010 17:49

Re: Pointer Problem
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.

All times are GMT +5.5. The time now is 14:27.