Variable Declaration & Initialization :: C++

Status
You're currently viewing only kuphryn's posts. Click here to go back to viewing the entire thread.
Not open for further replies.
Hi.

Conventionally speaking, do you declare and initialize variables at the beginning of a function or loop or right before usage.

For example:

int main()
{
char temp;

cin >> temp;
cout << "1234... & " << temp;

cin >> temp;
cout << temp;

int x;
cin >> x;
cout << temp << " & " << x;
return 0;
}

The arbitrary code above depicts declaration of variables right before usage (int x).

Which way is most convention is arguably better?

Thanks,
Kuphryn
 
Thanks!

As of today, I have begun to declare variable when:

1) there is something to initialize it with

int x = ...functure return, something added/subtract, etc, to other variables

2) right before its usage

int x = 3;
cout << x;

The only time I declare a variable at the top:

int x = 0;

is when it will be referenced to.

function(int &aboveX)
cout << aboveX;

So aboveX is a reference to x.

I began learning and practicing C++ about four months ago. I find something really interesting. I find that when you first learn C++ in college and reading beginner C++ books, the professor and author typically recommend declaring variables right at the top. They make it like it is imperative that we do that or the program may not work. Now, I feel that the programmer is in control of the program and that he/she can declare variables wherever is appropriate. As I mentioned, I feel it is much easier to recognize variable when the program declare them accord to the examples above.

Kuphryn
 
Stoffel posted something interesting. He responded to this same question and said:

"All memory for all variables in a function are allocated at the beginning of a function in a single step, period. You cannot allocate new stack variables in the middle of a function."

http://www.gamedev.net/community/forums/topic.asp?topic_id=71967

Is that a true statement?

Kuphryn
 
Status
You're currently viewing only kuphryn's posts. Click here to go back to viewing the entire thread.
Not open for further replies.