Question 9
Back to Exercise
What is the output of the following C program?
#include <stdio.h>
int main(void) {
int a = 10, b = -2;
int mask = -(a < b); /* all ones if a < b, else 0 */
int mn = b ^ ((a ^ b) & mask);
int mx = a ^ ((a ^ b) & mask);
printf("%d %d %d\n", mask, mn, mx);
return 0;
}
- A 0 -2 10 Correct
- B -1 10 -2
- C 0 10 -2
- D 1 -2 10
Correct Answer: Option A
a < b is false, so the mask is 0. Then b ^ 0 is b (the minimum, −2) and a ^ 0 is a (the maximum, 10). With a true comparison the mask would be −1 and the XORs would swap the values.
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!