Machine-translated by Google. Questions are authored in English.
Top

Discussion

What is the output of the following program?

#include <stdio.h>

void swap(int m, int n)
{
   int x = m;
   
   m = n;
   n = x;
}
main()
{
   int x=5, y=3;

   swap(x,y);
   printf("%d %d", x, y);
}

 

  • A.3 5
  • B.5 3
  • C.5 5
  • D.Compile error

Answer: B

Correct answer: 5 3

C passes arguments by value, so swap receives copies and exchanges the copies. The originals in main are untouched, and the output is 5 3. To swap the caller’s variables the function must take pointers and be called as swap(&x, &y).

No comment is present. Be the first to comment.
Loading…

Post your comment

Please log in or register to post a comment.