C Rapidfire 1

Look at the code, figure out the output, and then read the explanation to see if you got it right.

  1. 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 in 111, which is 7 in decimal.

  2. 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, so b * c is evaluated first, resulting in 1 + 6.

  3. 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 array arr, so *(ptr + 2) dereferences it, yielding 30.

  4. Sizeof Operator:

     int a = 10;
     printf("%zu\n", sizeof(a++));
    

    Output: 4 (assuming int is 4 bytes on the system) Explanation: sizeof operator doesn't evaluate its operand, so a is not incremented.

  5. 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.

  6. 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, whereas arr + 0 is a pointer.

  7. 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.

  8. Function Pointer:

     void fun() { printf("Hello World\n"); }
     void (*fun_ptr)() = &fun;
     (*fun_ptr)();
    

    Output: Hello World Explanation: fun_ptr is a pointer to function fun, and (*fun_ptr)() calls it.

  9. 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 of a and b.

  10. Macro Expansion:

    #define SQUARE(x) (x * x)
    int y = 5;
    printf("%d\n", SQUARE(y+1));
    

    Output: 11 Explanation: Macro expands to 5 + 1 * 5 + 1, which equals 11 due to lack of parentheses in the macro definition.