Variable Declaration & Initialization :: C++
-
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
-
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
See C++ FAQ Lite. HTH, --peter
-
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