C Rapidfire 3

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

Here are 10 additional challenging C code examples that demonstrate tricky aspects of the language:

  1. Logical vs Bitwise Operators:
int x = 1, y = 0;
if (x & y)
    printf("True\n");
else
    printf("False\n");

Output: False Explanation: The bitwise AND (&) of 1 and 0 is 0, hence the else branch is executed.

  1. Array Decay to Pointer:
int arr[] = {10, 20, 30};
int *p = arr;
printf("%d\n", sizeof(arr) / sizeof(arr[0]));

Output: 3 Explanation: sizeof(arr) gives the total size of the array, divided by the size of one element yields the number of elements.

  1. Sign Extension with Bit Fields:
struct {
    signed int x: 3;
} s;
s.x = 7;
printf("%d\n", s.x);

Output: -1 on many systems Explanation: Assigning 7 (111 in binary) to a 3-bit signed int can result in sign extension, interpreting it as -1.

  1. Character Pointer and String Literal:
char *str = "Hello";
printf("%s\n", str);

Output: Hello Explanation: str points to a string literal. String literals are stored in read-only memory.

  1. Integer Overflow:
unsigned int a = 4294967295; // Maximum value for a 32-bit unsigned int
a += 1;
printf("%u\n", a);

Output: 0 Explanation: Adding 1 to the maximum value of an unsigned int causes it to wrap around to 0.

  1. Function Pointer Syntax:
void greet() { printf("Hello\n"); }
void (*func_ptr)() = greet;
func_ptr();

Output: Hello Explanation: func_ptr is a pointer to the function greet and is used to call the function.

  1. Struct Initialization:
struct Point { int x, y; };
struct Point p = {.y = 20, .x = 10};
printf("%d %d\n", p.x, p.y);

Output: 10 20 Explanation: The struct Point is initialized with named members out of order, but they are correctly assigned.

  1. Implicit Type Conversion:
short s = 32767;
s += 1;
printf("%d\n", s);

Output: -32768 Explanation: Adding 1 to the maximum value of a short results in overflow, wrapping around to its minimum value.

  1. Macro Trick:
#define SQUARE(x) x*x
int a = 6 / SQUARE(2);
printf("%d\n", a);

Output: 3 Explanation: The macro expands to 6 / 2*2, which is evaluated as (6 / 2) * 2 due to operator precedence.

  1. Enum Constants:
enum { RED, GREEN, BLUE } color;
color = BLUE;
printf("%d\n", color);

Output: 2 Explanation: Enum constants RED, GREEN, BLUE are automatically assigned values 0, 1, 2 respectively.