Is this always going to run as expected?
char *x;
if (...) {
int len = dynamic_function();
char x2[len];
sprintf(x2, "hello %s", ...);
x = x2;
}
printf("%s\n", x);
// prints hello
How does the compiler (GCC in my case) implement variably sized arrays, in each of C and C++?
No.
x2is local to theifstatement’s scope and you access it outside of it using a pointer. This results in undefined behaviour.By the way, VLAs have been made optional in C11 and had never been part of C++. So it’s better to avoid it.