Why does the compiler allow initializing a variable with itself? [duplicate]

I don't see why it wouldn't compile. Definition happens prior to initialization. Of course this initialization is pointless, however, there's no reason it wouldn't work from the compilers stand point.

C does not have the same types of protections that more modern languages like C# have. The C# compiler would give an error that you're using an unassigned variable. C doesn't care. It will not protect you from yourself.


It's perfectly legitimate to use a variable in its own initializer. Consider a linked list:

#include <stdio.h>
struct node { struct node *prev, *next; int value; };
int main() {
    struct node l[] = {{0, l + 1, 42}, {l, l + 2, 5}, {l, 0, 99}};
    for (struct node *n = l; n; n = n->next)
        printf("%d\n", n->value);
    return 0;
}

In general, diagnosing when a value is used uninitialised is a difficult problem; although some compilers can detect it in some cases it doesn't make sense to require it to happen.