Bitwise Operators
| Operator | Meaning |
|---|---|
& |
bitwise AND |
| ` | ` |
^ |
bitwise XOR |
Operands must be integral types.
#include <stdio.h>
int main(void) {
int x = 1;
int y = 2;
x & y; /* 0 */
x | y; /* 3 */
x ^ y; /* 3 */
return 0;
}
Swapping Without a Temporary Variable
#include <stdio.h>
int main(void) {
int a = 10;
int b = 20;
a ^= b;
b ^= a;
a ^= b;
printf("a=%d b=%d\n", a, b); /* a=20 b^10 */
return 0;
}
Counting Set Bits in a Integer
/* Approach 1 – only for positive values */
#include <stdio.h>
int main(void) {
unsigned v = 10;
unsigned ones = 0;
while (v) {
ones += v & 1;
v >>= 1;
}
printf("ones = %u\n", ones);
return 0;
}
/* Approach 2 – works for any 32-bit int */
#include <stdio.h>
int main(void) {
int n = -1;
int ones = 0;
for (int k = 0; k < 32; ++k)
if (n & (1u << k))
++ones;
printf("ones = %d\n", ones);
return 0;
}
/* Approach 3 – Brian Kernighan’s algorithm */
#include <stdio.h>
int main(void) {
int n = -1;
int ones = 0;
while (n) {
n &= n - 1;
++ones;
}
printf("ones = %d\n", ones);
return 0;
}
Logical Operators
| Operator | Meaning |
|---|---|
&& |
logical AND |
| ` |
Differences from bitwise versions:
1 & 2 → 0
1 && 2 → 1
1 | 2 → 3
1 || 2 → 1
Short-circuit evaluation:
#include <stdio.h>
int main(void) {
int a = 0, b = 2, c = 3, d = 4;
int r = a++ && ++b && d++;
/* r = 0, a = 1, b, c, d unchanged */
printf("a=%d b=%d c=%d d=%d\n", a, b, c, d);
return 0;
}
Conditional Operator
/* Equivalent forms */
if (a > 5)
b = 3;
else
b = -3;
b = (a > 5) ? 3 : -3;
/* Maximum of two values */
max = (x > y) ? x : y;
Shift Operators
| Operator | Meaning |
|---|---|
<< |
left shift |
>> |
right shift |
Operands must be integers; the shift amount must be non-negative.
Left Shift Rules
Discard bits shifted out on the left; fill vacated bits on the right with 0.
Right Shift Rules
Two variants:
- Logical shift: fill vacated bits on the left with 0.
- Arithmetic shift: fill vacated bits on the left with the sign bit.
Unedfined behavior for negative shift counts:
int num = 10;
num >> -1; /* undefined */
Comma Operator
Syntax: exp1, exp2, …, expN
Expressions are evaluated left-to-right; the result is the value of the last expression.
int a = 1, b = 2;
int c = (a > b, a = b + 10, a, b = a + 1); /* c = 13 */
if (a = b + 1, c = a / 2, d > 0) { /* last expression controls if */ }
/* Loop rewritten with comma operator */
while (a = get_val(), count_val(a), a > 0) {
/* business logic */
}