Thread: C Puzzle -Need Help..

  1. #1
    C is Sea. I know a drop! ganesh bala's Avatar
    Join Date
    Jan 2009
    Location
    Bangalore
    Posts
    58

    C Puzzle -Need Help..

    Code:
    #include<stdio.h>
    
    #define MAX(x,y) ( x ) > ( y ) ? x:y
    main()
    { int i=10,j=5,k=0;
    k= MAX(i++,++j);
    printf("%d %d %d ",i,j,k);
    }
    
    Ans:12 6 11
    
    but i'm expecting value of i to be 11 can some one explain how it is 12 in this expression?

  2. #2
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    This is a classic case of macro expansion versus function call - since the macro expands the input parameter twice in the MAX() macro, it will increment one of the values twice.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  3. #3
    Registered User
    Join Date
    Jan 2009
    Posts
    20
    when compiling this line of code:
    Code:
     k= MAX(i++,++j);
    the compiler substitutes MAX with the macro you defined:
    Code:
     k= ( i++ ) > ( ++j ) ? i++ : ++j

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. The puzzle again...Swapping elements of 2D array
    By crazygopedder in forum C Programming
    Replies: 44
    Last Post: 11-05-2008, 01:53 PM
  2. Replies: 12
    Last Post: 06-06-2008, 05:26 PM
  3. Crossword Puzzle Program
    By Loctan in forum C++ Programming
    Replies: 2
    Last Post: 07-31-2006, 11:08 PM
  4. Solution to Google Puzzle 3,3,8,8=24
    By LuckY in forum A Brief History of Cprogramming.com
    Replies: 10
    Last Post: 06-01-2006, 09:12 AM