infoclogged
infoclogged

Reputation: 4007

Difference between #define and typedef when using its name to define a variable

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?

Upvotes: 2

Views: 466

Answers (3)

Rakete1111
Rakete1111

Reputation: 49008

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.

Upvotes: 1

user2672107
user2672107

Reputation:

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

Upvotes: 0

Jay Buckman
Jay Buckman

Reputation: 578

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.
}

Upvotes: 0

Related Questions