#1
  1. Banned ;)
    Devshed Supreme Being (6500+ posts)

    Join Date
    Nov 2001
    Location
    Woodland Hills, Los Angeles County, California, USA
    Posts
    9,638
    Rep Power
    4247

    Puzzle of the Week/Month/Whenever Ol' Scorps gets around to it


    Well folks, I'm back from my NY vacation and ready for another puzzle. This one is based on an actual production issue I found before my vacation. It is fairly simple. The goals are to:
    (a) guess what value will be printed out.
    (b) explain why it works that way.
    (c) explain how to fix it.
    and most valuable of all
    (d) educate beginners to C code :)

    Code:
    #include <stdio.h>
    
    void increment(int *p);
    
    int main(void)
    {
        int a = 1;
    
        increment(&a);
        increment(&a);
        increment(&a);
    
        /* What is the value that will be printed */
        printf("The value of a is %d\n", a);
        return 0;
    }
    
    void increment(int *p)
    {
        *p++;
    }
    Usual contest rules apply (i.e.) people who post correct answers get to be on my signature for a week/month/until I get around to posting the next puzzle.
    Up the Irons
    What Would Jimi Do? Smash amps. Burn guitar. Take the groupies home.
    "Death Before Dishonour, my Friends!!" - Bruce D ickinson, Iron Maiden Aug 20, 2005 @ OzzFest
    Down with Sharon Osbourne

    "I wouldn't hire a butcher to fix my car. I also wouldn't hire a marketing firm to build my website." - Nilpo
  2. #2
  3. No Profile Picture
    Closet coder
    Devshed Beginner (1000 - 1499 posts)

    Join Date
    Feb 2005
    Location
    Plantation, FL <---south florida
    Posts
    1,431
    Rep Power
    153
    a. prints 1
    b. order of operations for *p++
    c. parentheses FTW
    d. GOTO c.
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jun 2007
    Posts
    16
    Rep Power
    0
    a. 1
    b. because *p++; is actually like:
    *p;
    p = p + 1;
    that is the post ++ operation takes the minimal preciding variable

    c & d: possible solutions
    Code:
    void increment(int *p)
    {
        (*p)++;
        /* is equal to 
        *p;
        *p = *p +1;
        */
    }
    or
    Code:
    void increment(int *p)
    {
        ++*p;
        /* is equal to 
        *p = *p + 1;    // eh,, edited typo
        *p;
        */
    }

IMN logo majestic logo threadwatch logo seochat tools logo