C Rapidfire 1
Look at the code, figure out the output, and then read the explanation to see if you got it right.
Bitwise Puzzle:
int x = 5; int y = x | 2; printf("%d\n", y);
Output:
7
Explanation: The bitwise OR (|
) operation between 5 (101
in binary) and 2 (010
in binary) results in111
, which is 7 in decimal.Operator Precedence:
int a = 1, b = 2, c = 3; int result = a + b * c; printf("%d\n", result);
Output:
7
Explanation: Multiplication has higher precedence than addition, sob * c
is evaluated first, resulting in1 + 6
.Pointer Arithmetic:
int arr[] = {10, 20, 30}; int *ptr = arr; printf("%d\n", *(ptr + 2));
Output:
30
Explanation:ptr + 2
points to the third element of the arrayarr
, so*(ptr + 2)
dereferences it, yielding30
.Sizeof Operator:
int a = 10; printf("%zu\n", sizeof(a++));
Output:
4
(assumingint
is 4 bytes on the system) Explanation:sizeof
operator doesn't evaluate its operand, soa
is not incremented.Comma Operator:
int x = (5, 10); printf("%d\n", x);
Output:
10
Explanation: The comma operator evaluates each of its operands and returns the last one.Array-to-Pointer Decay:
char arr[] = "Hello"; printf("%zu\n", sizeof(arr)); printf("%zu\n", sizeof(arr + 0));
Output:
6
and size of pointer (e.g.,8
on a 64-bit system) Explanation:sizeof(arr)
gives the size of the array including the null terminator, whereasarr + 0
is a pointer.Conditional Operator:
int x = 1, y = 2; int max = (x > y) ? x : y; printf("%d\n", max);
Output:
2
Explanation: It's a simple use of the ternary operator for finding the maximum.Function Pointer:
void fun() { printf("Hello World\n"); } void (*fun_ptr)() = &fun; (*fun_ptr)();
Output:
Hello World
Explanation:fun_ptr
is a pointer to functionfun
, and(*fun_ptr)()
calls it.Struct Padding:
struct { char a; int b; } s; printf("%zu\n", sizeof(s));
Output: Typically
8
on many systems Explanation: Due to padding for alignment, the size is more than the sum of sizes ofa
andb
.Macro Expansion:
#define SQUARE(x) (x * x) int y = 5; printf("%d\n", SQUARE(y+1));
Output:
11
Explanation: Macro expands to5 + 1 * 5 + 1
, which equals 11 due to lack of parentheses in the macro definition.