Is writing to &str[0] buffer (of a std:string) well-defined behaviour in C++11?

Yes, the code is legal in C++11 because the storage for std::string is guaranteed to be contiguous and your code avoids overwriting the terminating NULL character (or value initialized CharT). From N3337, §21.4.5 [string.access] const_reference operator[](size_type pos) const; reference operator[](size_type pos); 1 Requires: pos <= size(). 2 Returns: *(begin() + pos) if pos < size(). … Read more

Is it safe to memset bool to 0?

Is it guaranteed by the law? No. C++ says nothing about the representation of bool values. Is it guaranteed by practical reality? Yes. I mean, if you wish to find a C++ implementation that does not represent boolean false as a sequence of zeroes, I shall wish you luck. Given that false must implicitly convert … Read more

Can using a lambda in header files violate the ODR?

This boils down to whether or not a lambda’s type differs across translation units. If it does, it may affect template argument deduction and potentially cause different functions to be called – in what are meant to be consistent definitions. That would violate the ODR (see below). However, that isn’t intended. In fact, this problem … Read more

Can branches with undefined behavior be assumed unreachable and optimized as dead code?

Does the existence of such a statement in a given program mean that the whole program is undefined or that behavior only becomes undefined once control flow hits this statement? Neither. The first condition is too strong and the second is too weak. Object access are sometimes sequenced, but the standard describes the behavior of … Read more

How do I make an infinite empty loop that won’t be optimized away?

The C11 standard says this, 6.8.5/6: 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 for statement) its expression-3, may be assumed by the implementation … Read more

Initialization vs Assignment in C

In the C Standard, only option (1) is initialization. In programming jargon, both may be considered initialization. Your question is really asking about the meanings of words. It’s normal for people to use words with various common meanings, instead of switching terminology for particular languages. Another example is “pass by reference”. Does C have pass … Read more

What happened to the “aggregate or union type that includes one of the aforementioned types” strict aliasing rule?

The lvalue you use to access the stored value of y is not *reinterpret_cast<Foo*>(&y), of type Foo, but it is reinterpret_cast<Foo*>(&y)->x, which has the type float. Accessing a float using an lvalue of type float is fine. In C++, you can not “access the value of a union or struct” (as whole), you can only … Read more

tech