Skip to main content
GameDev.net gamedev.net
🔒 Locked

Where are variable declarations valid?

Started by drslush May 20, 2003 at 11:18 AM 4 replies 250+ views
Original Post
drslush
drslush
In C++, where is it legal to declare a variable? Obviously, you can declare a variable in the initialization of a "for" loop, but no where else in an expression. Is the initialization of a "for" loop a special expression that has an exception? The reason I want to know is because I am making a scripting language that uses syntax similar to C++.
civguy
civguy

if (int a = 1) {
a = 2;
}
Khaos Dragon
Khaos Dragon
quite generally variable declarations in c++ (unlike c) can happen almost anywhere, but I''m sure someone can provide some specifics.

The code above assigns 1 to a and the whole statement is evaluated as an expression returning true, thus a is then assigned 2.
drslush
drslush
Well I need to have predefined variables, otherwise I get a real performance hit (Since the variables are already declared in a function, I can use an index into an array instead of having to use a hash every time a variable is used).

I know I can''t do something like:

cout << (int a = 1) << endl;

But I can do:

for(int a=0; a<10; a++) cout << "Hello";

So what are the rules for where a variable can be defined?
rohde
rohde
Where ever you can have a statement....

-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
Any intelligent fool can make things bigger, more complex, and more violent. It takes a touch of genius -- and a lot of courage -- to move in the opposite direction.
"We confess our little faults to persuade people that we have no large ones." -Francois de La Rochefoucauld (1613 - 1680). | My blog

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.