C Rapidfire 2

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

  1. Floating Point Precision:
double a = 0.7;
if (a < 0.7)
    printf("Less than 0.7\n");
else
    printf("Not less than 0.7\n");

Output: Less than 0.7 Explanation: 0.7 is treated as a double in the variable a but as a float in the comparison, leading to a precision mismatch.

  1. Shift Operator Behavior:
int x = 1;
printf("%d\n", x << 32);

Output: Depends on the system (could be 1 or 0) Explanation: Shifting by the bit width of the type or more yields undefined behavior in C.

  1. Character Arrays and Null Terminator:
char str[6] = "hello";
printf("%s\n", str);

Output: hello Explanation: The string "hello" fits exactly into str, including the null terminator, which is implicitly added.

  1. Integer Promotion in Variadic Functions:
printf("%lu\n", sizeof('A'));

Output: 4 or 8 (depending on the system) Explanation: Character constants are promoted to int in C, and sizeof returns the size of int.

  1. Volatile Keyword:
volatile int x = 10;
x = 20;
x = 30;
printf("%d\n", x);

Output: 30 Explanation: The volatile keyword prevents the compiler from optimizing out multiple assignments to x, ensuring the last value is printed.

  1. Array Initialization:
int arr[5] = {1, 2, 3};
printf("%d %d\n", arr[3], arr[4]);

Output: 0 0 Explanation: Uninitialized elements in an array initializer list are automatically set to zero.

  1. Pointer and Array Relationship:
int arr[] = {10, 20, 30, 40, 50};
int *p = arr;
printf("%d\n", p[3]);

Output: 40 Explanation: p points to the array arr, so p[3] is equivalent to arr[3].

  1. Static Variable in Function:
void func() {
    static int count = 0;
    count++;
    printf("%d ", count);
}
func();
func();

Output: 1 2 Explanation: The static variable count retains its value between function calls.

  1. Struct and Union Difference:
union {
    int a;
    char b;
} u;
u.a = 1;
printf("%d\n", u.b);

Output: 1 or 0 (depends on system endianness) Explanation: In a union, all members share the same memory. The output depends on how integers are stored in memory (endianness).

  1. Pre-increment and Post-increment:
int i = 1;
printf("%d %d\n", i, i++);

Output: 2 1 Explanation: The value of i is incremented before it's passed to printf, but the original value (1) is used in the expression due to post-increment.