C Programming Language Quiz

https://lobste.rs/rss Hits: 37
Summary

This quiz is about quirks of the programming language C and intended for fun and educational purpose. The one or the other question is more academic, i.e., it should make you think ;-) If two pointers p and q of the same type point to the same address, then p == q must evaluate to true. Short answer: Comparing two pointers which are derived from two different objects which are not part of the same aggregate or union object invokes undefined behavior. Have a look at this post for a detailed discussion. Consider the following code snippet where an object of type int is accessed through lvalues of type short and unsigned char: int i = 42; short *s = (short *) &i; unsigned char *c = (unsigned char *) &i; *s; // (A) *c; // (B) (A) and (B) invoke undefined behavior (A) invokes undefined behavior but (B) is legal (B) invokes undefined behavior but (A) is legal (A) and (B) are legal The rule of thumb is: accessing an object of type T through an lvalue of type U where T and U are not compatible (modulo few exceptions) invokes undefined behavior—according to the strict aliasing rules. That means, in the example we accessed an object of type int through an lvalue of type short which leads to undefined behavior. One exception to the rule is that a character pointer may alias any other pointer, i.e., any object may be accessed through a character pointer. Note, only type unsigned char is guaranteed to have no padding bits and therefore has no trap representation which could invoke undefined behavior (since C11 also signed char is guaranteed to have no padding bits). Thus (A) invokes undefined behavior whereas (B) is legal. Have a look at this post for a detailed discussion. It may make a difference whether an integer constant is given in decimal or hexadecimal format. In other words the meaning may be different. In a nutshell the type of an unsuffixed decimal constant is always signed whereas of a hexadecimal constant the type may be signed or unsigned. C17 § 6.4.4.1 Integer con...

First seen: 2026-05-22 08:15

Last seen: 2026-05-23 20:43