Thread: macro function result

  1. #1
    Registered User
    Join Date
    Oct 2022
    Posts
    92

    macro function result

    I'm looking your expertise to help me understand why the output is not as expected.

    Code:
    #include <stdio.h>
    
    #define SQUARE(x) (x)*(x)
    
    
    int main()
    {
        printf("%d ", SQUARE(4));    //  16
        int x = 3;                   // x = 3 
        printf("%d ", SQUARE(++x));  // Expecting 16 but getting 25 
       
    
    
        return 0;
    }


    Why program give value 25 instead of 16

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    This is what the compiler sees after the pre-processor has done it's evil thing.
    Code:
    $ gcc -E foo.c | tail
    int main()
    {
        printf("%d ", (4)*(4));
        int x = 3;
        printf("%d ", (++x)*(++x));
    
    
    
        return 0;
    }
    This is what the compiler thinks about it.
    Code:
    $ gcc -Wall foo.c
    foo.c: In function ‘main’:
    foo.c:10:26: warning: operation on ‘x’ may be undefined [-Wsequence-point]
       10 |     printf("%d ", SQUARE(++x));  // Expecting 16 but getting 25
          |                          ^
    foo.c:3:20: note: in definition of macro ‘SQUARE’
        3 | #define SQUARE(x) (x)*(x)
          |                    ^
    The problem is, your macro expansion ends up doing ++x twice, so you're surprised by the result.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    May 2012
    Location
    Arizona, USA
    Posts
    948
    To be clear, (++x)*(++x) is undefined behavior because you cannot modify the same object more than once between sequence points. You can't and shouldn't expect any particular result from undefined behavior. It might even cause demons to fly out of your nose, which is usually not what one would expect.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. How to get result from display function ?
    By gajya in forum C Programming
    Replies: 3
    Last Post: 11-20-2019, 04:50 AM
  2. Replies: 4
    Last Post: 02-23-2016, 11:48 AM
  3. Function result as a string
    By nowber in forum C Programming
    Replies: 6
    Last Post: 10-28-2009, 05:40 AM
  4. Help understanding result of Function
    By deadhippo in forum C Programming
    Replies: 7
    Last Post: 04-05-2008, 02:56 AM
  5. Macro has same name as Function?
    By coolclu3 in forum C Programming
    Replies: 10
    Last Post: 09-28-2007, 04:55 AM

Tags for this Thread