Declaring variables and you..

I recently finished the tutorials and am now going through the C++ Primer Plus 3rd edition. The book states that it is standard practice for variables to be declared just before they are used. Is this the case in a professional environment? From what I have seen programs typically start with the declaration of variables right after the function is created.So:

1
2
3
4
5
6
7
8
9
10
int main()
{
  //declare variable
  //declare variable
  //declare variable

  //Use variable in statement
  //Use variable in statement
  //Use variable in statement
}


vs

1
2
3
4
5
6
7
8
9
10
11
int main()
{
  //declare variable
  //use variable in statement

  //declare variable
  //Use variable in statement

  //declare variable
  //Use variable in statement
}


I really don't want to develop any bad habits so a little guidance would be appreciated. Thanks.
Your first example is the way you must do it in C; the language requires in that way.

In C++, the best practice is to minimize the scope of your variables, which is your
second example (though in C++ it is best to declare and initialize in the same line).
You should follow the best practice unless your company explicitly forbids it (in
which case look for a new job).
try to think off all the variables you will need in program...

if u can ,,,
.
.
But I even use the 2nd method u have shown,,, ... declaring the variables as in pic 1, will make you code more neat ,,,
.
.
I recommend the 2nd type of declaring ...
Ok thank you that was helpful and also explains the variance with what I have seen.
Topic archived. No new replies allowed.