Where to declare variables - Best Practise

This is a discussion on Where to declare variables - Best Practise within the C++ Programming forums, part of the General Programming Boards category; Hi, In University we have been taught to declare variables at the top, eg: Code: int x; int y; string ...

  1. #1
    Registered User
    Join Date
    Feb 2009
    Posts
    329

    Where to declare variables - Best Practise

    Hi,

    In University we have been taught to declare variables at the top, eg:

    Code:
    int x;
    int y;
    string name;
    etc.......
    However, working through Accelerated C++, they use a different approach, for example:

    Code:
    cout << "Please enter your name: "
    string name;
    cin >> name;
    Which is the better option here? I prefer the second as taught in ACPP.

    Thanks.

  2. #2
    The larch
    Join Date
    May 2006
    Posts
    3,573
    In C++ declare variables close to first use and also initialize them (not necessary here as you are going to input to the string right away and string is default-initialized anyway).

    What you are being taught follows the rules of C (before the 1999 standard) where you simply don't have a choice as variables must be declared as the first thing in the scope. This, as I understand, was so mainly for technical reasons to help compilers of the time (perhaps the only "advantage" is that you can find the declarations in a function at the same place).

    In C++ you won't be able to follow this rule consistently anyway (without perhaps creating artificial scopes), as you might have objects that only allow declaration and initialization with meaningful values, and those meaningful values might be computed later in the function body.
    I might be wrong.

    Thank you, anon. You sure know how to recognize different types of trees from quite a long way away.
    Quoted more than 1000 times (I hope).

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 15
    Last Post: 09-30-2008, 02:12 AM
  2. esbo's data sharing example
    By esbo in forum C Programming
    Replies: 49
    Last Post: 01-08-2008, 10:07 PM
  3. Creating local variables in a program?
    By fl0at in forum C Programming
    Replies: 5
    Last Post: 01-04-2008, 06:34 PM
  4. Global Variables
    By Taka in forum C Programming
    Replies: 34
    Last Post: 11-02-2007, 03:25 AM
  5. functions to return 2 variables?
    By tim in forum C Programming
    Replies: 5
    Last Post: 02-18-2002, 01:39 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21