2

This is a follow up to this question right here.

typedef int foo;
#define bar int

int main() {
    bool foo = true; // ok
    bool bar = true; // fail
}

the typedef works, but I am curious to know how can the typedef here work?

How does the final compiled code looks like with respect to foo? According to few answers, typedef is an alias and alias is allowed to be shadowed. Hence the code works.

Can anyone please explain?

Rakete1111
  • 47,013
  • 16
  • 123
  • 162
infoclogged
  • 3,641
  • 5
  • 32
  • 53

3 Answers3

1

Type names in general are allowed to be used to define a variable with the same name What I mean is this:

typedef int foo; // can't be in the same scope as the below definitions
struct foo { foo(int) {} }; // same thing as above

int foo = 0; // ok
foo bar = 1; // ok
foo foo = 2; // ok

But with #define foo int, there is no foo type/alias:

#define foo int
int foo = 0; // fail
foo bar = 1; // ok
foo foo = 2; // fail

The above is actually (after the preprocessor runs):

int int = 0; // fail
int bar = 1; // ok
int int = 2; // fail

If you had another definition, bool foo = true;, then it will become bool int = true;, which also fails to compile.

But there is an exception: int is a reserved keyword, which means you can't define any variables with that name. But if it were another type like struct bar{};, then that part will compile.

Rakete1111
  • 47,013
  • 16
  • 123
  • 162
0

The first works because you are supplying a type and not using the typedef. The second fails because the macro is substituting int for bar.

typedef int foo;
#define bar int

int main() {
    bool foo = true; // ok   
           // You have created a new bool variable named foo.
           // There is no relation to the typedef foo.
    bool bar = true; // fail
           //  Essentially you are saying
           //           bool int = true;
           //  which doesn't compile - you can't have a variable named
           //  int because it's a reserved keyword.
}
Jay Buckman
  • 581
  • 5
  • 18
  • 1
    I think the question really is *Why is there no relation to the `typedef` foo?* I.e. what does the `typedef` really doing? – Walter Jun 23 '17 at 11:00
  • @Walter typedef cannot create new language keywords, so it's not a problem to reuse those words. – Mr Lister Jun 23 '17 at 11:15
0

I variable may have the same name as a type: you have an unused type foo and a variable foo with type bool.