LB40
LB40

Reputation: 12331

Is there a way to know if a variable has been declared in C?

I'm implementing some code generators, i would like to know if there's any way in C, if a variable has already been declared ?

I was trying to find something using the preprocessor but without any success...

thanks.

Upvotes: 1

Views: 3641

Answers (5)

user8559613
user8559613

Reputation:

i'm pretty late, well there is an easy way to know this, with text files; write the variable name inside a file right when you declare it, and then check later if the name is written. just make 3 macros "DEF" "IF_DEF" and "IF_NOT_DEF" and it looks good. You can't look up in C, but you can look up inside a file. But it does take some memory.

Upvotes: 0

Rudi
Rudi

Reputation: 19940

Is the variable itself generated by your generator or something the user enters? When you generate the variable youself you can emmit a preprocessor token along with the variable and later check if that token exist.

Upvotes: 0

sbi
sbi

Reputation: 224119

No, there isn't. Doing so is much of what compilers do.

A common way to create unique a variable name is to use a very unlikely variable name, if possible combined with the line number. Something like

// beware, brain-compile code ahead!
a_rather_unlikely_variable_name_by_sbi_ ## __LINE__

Upvotes: 2

T.E.D.
T.E.D.

Reputation: 44804

Not really, no. Not unless you count attempting to use it and seeing if your code compiles.

You could try to hack something with the preprocessor for specific variables, sort of like the standard #ifdef at the top of every include file. That wouldn't be scope-aware though, as the preprocessor runs way before the compiler does.

C isn't a very dynamic language that way.

Upvotes: 0

Abbas
Abbas

Reputation: 6886

C is strictly static, you can't "lookup" if a variable has already been declared. If you are creating a code generator, why not read lines of code and see what's been declared?

Upvotes: 5

Related Questions