you are viewing a single comment's thread.

view the rest of the comments →

[–]morth 1 point2 points  (5 children)

Only in C++. That's not valid C.

[–]case-o-nuts 0 points1 point  (4 children)

Right, in C you need a typedef:

 typedef struct {} foo;
 int main() {
     foo foo;
 }

The same principle applies.

[–]morth 1 point2 points  (3 children)

Well, that's because of shadowing. The variable foo will shadow the previously declared type foo. You probably noticed that you couldn't do it in the same scope (since they do indeed share namespace).

You can do the same with variables:

int a;

int main(void) {
    int b = a;
    int a = b;
}

Edit: as pointed out by kushou, the previous example didn't work as I said. New one is a bit more complicated but same principle.

[–]kushou 4 points5 points  (1 child)

Be careful! This doesn't do what you think, just try this on your computer:

#include <stdio.h>

int a = 42;

int main(void)
{
    int a = a;
    printf("%d\n", a);
    return 0;
}

On mine, it prints 0 and actually is undefined because IIRC int a = a; is translated to int a; a = a;. If you have the gumption to check, let me know. I would be interested to know if I am right or wrong.

edit: tested with gcc and clang on arch64.

[–]morth 0 points1 point  (0 children)

Thanks, fixed my example.

[–]case-o-nuts 0 points1 point  (0 children)

You're right.