Thread: Macro Expansion

  1. #1
    Anirban Ghosh
    Join Date
    Jan 2006
    Posts
    278

    Macro Expansion

    Can anyone please explain the output of the following code. I failed to explain myself.

    Code:
    #include <stdio.h>
    
    #define SWAP(x,y) { int temp = x; printf("%d %d\n",x,y); x = y; printf("%d %d\n",x,y); y = temp; printf("%d %d\n",x,y);}
    
    int main()
    {
    	int temp = 1;
    	int b = 2;
    	
    	SWAP(temp,b);
    	
    	printf("%d %d\n",temp,b);
    	
    	return 0;
    }

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    Which version do you want?

    The obvious answer, which involves changing the name of the variable in main to be something other than temp, so you end up with say SWAP(a,b)

    Or the less obvious answer which involves explaining all about scope and declaration hiding because you have 'temp' in two different scopes.

    Try this (lookup how your compiler does this if you're not using gcc)
    gcc -E prog.c > prog.i

    Now look at prog.i in a text editor.
    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
    Anirban Ghosh
    Join Date
    Jan 2006
    Posts
    278
    Thanks.

    Why is it so that if I write

    Code:
    int temp = temp;
    the value of temp is 0.

  4. #4
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    > the value of temp is 0.
    Or garbage.

    That it is consistently zero for you at the moment is just dumb luck.
    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.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Expansion Crystal and AGP
    By jrahhali in forum Tech Board
    Replies: 0
    Last Post: 08-17-2011, 08:04 AM
  2. Laplace Expansion
    By Leojeen in forum C Programming
    Replies: 7
    Last Post: 10-28-2008, 11:26 PM
  3. Macro expansion
    By onebrother in forum C Programming
    Replies: 1
    Last Post: 11-02-2007, 03:08 AM
  4. taylor series expansion
    By noor_mirza in forum C++ Programming
    Replies: 1
    Last Post: 10-23-2002, 10:02 PM
  5. Expansion
    By Generator in forum A Brief History of Cprogramming.com
    Replies: 15
    Last Post: 10-02-2001, 05:45 AM