LearnFrenzy
Sign in Take a free test

Bitwise Operators · Bit Manipulation Programs · Question 8

Check whether two integers have opposite signs in C Solution, output & explanation

  • Program
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 8 Back to Exercise

Check whether two integers have opposite signs with a single bitwise expression.

Solution
main.c
#include <stdbool.h>
#include <stdio.h>

bool opposite_signs(int a, int b) {
    return (a ^ b) < 0;          /* sign bit of the XOR is 1 only if the sign bits differ */
}

int main(void) {
    int pairs[][2] = {{5, -3}, {-4, -9}, {7, 0}};
    for (int i = 0; i < 3; i++)
        printf("%d, %d: %s\n", pairs[i][0], pairs[i][1],
               opposite_signs(pairs[i][0], pairs[i][1]) ? "opposite" : "same");
    return 0;
}

Output Verified by compiling and running

5, -3: opposite
-4, -9: same
7, 0: same

The sign bit of a ^ b is 1 exactly when one number is negative and the other is not. Unlike a * b < 0, it cannot overflow. Zero counts as non-negative.

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