Problem with pointers

This is a discussion on Problem with pointers within the C Programming forums, part of the General Programming Boards category; Hi, I am having the following problem. Assume the code: int i = 4, j = 7; int *p = ...

  1. #1
    Registered User
    Join Date
    Apr 2010
    Posts
    3

    Problem with pointers

    Hi, I am having the following problem. Assume the code:

    int i = 4, j = 7;
    int *p = &i, *q = &j;
    i = (*p)++ + *q;

    After that, variable i will take value 12, right? Now, assume the following modification:

    int i = 4, j = 7;
    int *p = &i, *q = &j;
    i = (*p)++ * *q;

    Following the same reasoning, variable i would be equal to 29.

    However, using gcc (linux), variable i is equal to 5 in both cases!!! Under windows, I get 12 and 18, respectively!

    Does anyone know why???
    Thanks in advance!

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    22,269
    If we remove the pointers, first snippet is effectively equivalent to:
    Code:
    int i = 4, j = 7;
    i = i++ + j;
    The second snippet is effectively equivalent to:
    Code:
    int i = 4, j = 7;
    i = i++ * j;
    So, in both cases i is read twice and modified within consecutive sequence points. This results in undefined behaviour.
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    Registered User
    Join Date
    Apr 2010
    Posts
    3
    Thanks!
    Let me see of I got it. The sufix operator ++ modifies i only after solving the expression, but the value of i is read before solving.

  4. #4
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    22,269
    Quote Originally Posted by thennecy
    Let me see of I got it. The sufix operator ++ modifies i only after solving the expression, but the value of i is read before solving.
    No. Take a look at this series of FAQs: C Expressions.
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Problem with file handling (pointers)
    By hmk in forum C Programming
    Replies: 5
    Last Post: 09-19-2008, 11:03 AM
  2. Problem with pointers
    By kotoko in forum C Programming
    Replies: 3
    Last Post: 06-12-2008, 06:17 AM
  3. A problem with pointers
    By vsla in forum C Programming
    Replies: 2
    Last Post: 10-10-2007, 05:14 AM
  4. Returning pointer to array of pointers problem
    By jimzy in forum C Programming
    Replies: 15
    Last Post: 11-11-2006, 06:38 AM
  5. Problem writing swap using pointers
    By joshdick in forum C++ Programming
    Replies: 1
    Last Post: 02-29-2004, 10:06 PM

Tags for this Thread


1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21