LearnFrenzy
Sign in Take a free test

Decision Making · Predict the Output · Question 9

Branchless min and max with masks – output Answer, explanation & discussion

  • Output
  • Hard
  • 0 comments
  • Answer explained
  • Moderated community
Question 9 Back to Exercise

What is the output of the following C program?

main.c
#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!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links