Is while(1); undefined behavior in C?

It is well defined behavior. In C11 a new clause 6.8.5 ad 6 has been added An iteration statement whose controlling expression is not a constant expression,156) that performs no input/output operations, does not access volatile objects, and performs no synchronization or atomic operations in its body, controlling expression, or (in the case of a … Read more

Do I need to cast to unsigned char before calling toupper(), tolower(), et al.?

Yes, the argument to toupper needs to be converted to unsigned char to avoid the risk of undefined behavior. The types char, signed char, and unsigned char are three distinct types. char has the same range and representation as either signed char or unsigned char. (Plain char is very commonly signed and able to represent … Read more

Is it defined behavior to reference an early member from a later member expression during aggregate initialization?

Your second case is undefined behavior, you are no longer using aggregate initialization, it is still list initialization but in this case you have a user defined constructor which is being called. In order to pass the second argument to your constructor it needs to evaluate foo.i but it is not initialized yet since you … Read more

How does pointer comparison work in C? Is it ok to compare pointers that don’t point to the same array?

According to the C11 standard, the relational operators <, <=, >, and >= may only be used on pointers to elements of the same array or struct object. This is spelled out in section 6.5.8p5: When two pointers are compared, the result depends on the relative locations in the address space of the objects pointed … Read more

Incorrect cast – is it the cast or the use which is undefined behavior

The cast itself has undefined behaviour. Quoting C++17 (n4659) [expr.static.cast] 8.2.10/11: A prvalue of type “pointer to cv1 B”, where B is a class type, can be converted to a prvalue of type “pointer to cv2 D”, where D is a class derived (Clause 13) from B, if cv2 is the same cv-qualification as, or … Read more

Is right shift undefined behavior if the count is larger than the width of the type?

The draft C++ standard in section 5.8 Shift operators in paragraph 1 says(emphasis mine): The type of the result is that of the promoted left operand. The behavior is undefined if the right operand is negative, or greater than or equal to the length in bits of the promoted left operand. So if unsigned int … Read more

May I treat a 2D array as a contiguous 1D array?

Both lines do result in undefined behavior. Subscripting is interpreted as pointer addition followed by an indirection, that is, a[0][1234]/p[1234] is equivalent to *(a[0] + 1234)/*(p + 1234). According to [expr.add]/4 (here I quote the newest draft, while for the time OP is proposed, you can refer to this comment, and the conclusion is the … Read more