Given below are three implementations of swap() in C++:
(a) void swap(int a, int b) { int temp; temp = a; a = b; b = temp; } called as swap(p, q);
(b) void swap(int &a, int &b) { int temp; temp = a; a = b; b = temp; } called as swap(p, q);
(c) void swap(int *a, int *b) { int *temp; temp = a; a = b; b = temp; } called as swap(&p, &q);with int p = 0, q = 1 in main(). Which of these would actually swap the contents of p and q?
Pick an option to check yourself, or open the answer below.
Show answer & explanation
Correct answer: B. (b) only
Explanation
(a) swaps copies. (b) swaps through references, so p and q change. (c) swaps only the local pointer copies, never *a and *b, so p and q are untouched.
More Programming Languages and Computer Graphics questions
- In Java, which of the following statements is/are True ? S1 : The ‘final’ keyword applied to a class definition prevents the class from bei…
- Which of the following statements is/are True ? P : C programming language has a weak type system with static types. Q : Java programming l…
- A graphic display system has a frame buffer that is 640 pixels wide, 480 pixels high and 1 bit of color depth. If the access time for each…
- Which of the following statements is/are True regarding the solution to the visibility problem in 3D graphics ? S1 : The Painter’s algorith…
- Consider the matrix M = [2 0 2; 0 1 1; 0 0 1] representing a set of planar (2D) geometric transformations in homogeneous coordinates. Which…
- What is the output of the following C program? (Assume little-endian representation, with the least significant byte at the lowest address,…