Thread: Where to declare variables - Best Practise

  1. #1
    Registered User
    Join Date
    Feb 2009

    Where to declare variables - Best Practise


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

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

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


  2. #2
    The larch
    Join Date
    May 2006
    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, 11:07 PM
  3. Creating local variables in a program?
    By fl0at in forum C Programming
    Replies: 5
    Last Post: 01-04-2008, 07: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, 02:39 PM