Self-referential variable initialization in C
I was reading the SDL Shader Language Quickstart, which (at the moment) mostly consists of explanations about how the language differs from C.
One difference listed caught my eye: variable initialization can't reference itself. To quote,
Why does C even allow this?
int x = x + 1;
In C, x is in scope as soon as the parser sees int x, but this allows you to reference a variable that is definitely not initialized during its own initializer! Doing so is always a bug, so we just don't allow it.
I would consider myself fairly knowledgeable about the weird corners of C, but I had never come across this "feature"!
As stated, using the uninitialized value of the variable is going to be undefined behaviour in C. However, I did not immediately see why taking a pointer to the variable would be. So, as long as we only use the pointer of the value in its definition, that ought to be fine?
Normally, doing
type x = &x;
is going to fail because the types type
and type*
are not compatible.
However, in C (but not C++!) you can implicitly cast between void*
and
any other pointer type, including void**
.
This means we should be able to do
void *x = &x;
To test this, I made the following test program
#include <stdio.h>
int main(void) {
void *x = &x;
// We need an explicit cast for &x here, since printf is a
// varargs function.
printf("x = %p, &x = %p\n", x, (void*)&x);
}
And with GCC 14.2.0, this does indeed work, with zero warnings with the
flags -std=c23 -Wall -Wextra -pedantic
!