1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

Pointer Problem

Discussion in 'C' started by rezaxyz, Jun 24, 2010.

  1. rezaxyz

    rezaxyz New Member

    Joined:
    Jun 24, 2010
    Messages:
    1
    Likes Received:
    0
    Trophy Points:
    0
    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
     
  2. cfsantos

    cfsantos New Member

    Joined:
    Jun 24, 2010
    Messages:
    1
    Likes Received:
    0
    Trophy Points:
    0
    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
     
  3. xpi0t0s

    xpi0t0s Mentor

    Joined:
    Aug 6, 2004
    Messages:
    3,012
    Likes Received:
    203
    Trophy Points:
    0
    Occupation:
    Senior Support Engineer
    Location:
    England
    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.
     

Share This Page