Puzzle P19

classic swap mistake

The classic swap mistake

In the following, main() calls swap() to reverse the values in the variables a and b. But what really happens?

#include <stdio.h>

void swap( int x, int y )  
{
  int temp;

  printf("  x=%d  y=%d\n", x, y ) ;
  temp = x;
  x = y;
  y = temp;
  printf("  x=%d  y=%d\n", x, y ) ;
   
}

void main ( void )
{
  int a = 44, b = 77 ;

  printf("a=%d  b=%d\n", a, b ) ;
  swap( a, b ) ;
  printf("a=%d  b=%d\n", a, b ) ;
}

This puzzle shows a classic C programming error. Be sure you understand what goes wrong.



Previous Page        Answer         Next Page         Home