#1
  1. No Profile Picture
    PerlGuy
    Devshed Novice (500 - 999 posts)

    Join Date
    Jan 2001
    Posts
    720
    Rep Power
    42

    Variable Declaration


    Do all variables for a given program have to be declared at the beginning of that program?

    I'm guessing yes cuz I get this error:
    Code:
    `j' undeclared (first use in this function)
    when I declare the variable anywhere else.

    Anyone know offhand why all variable must be done in the beginning if this is the case?
    - dsb -
    Perl Guy
  2. #2
  3. Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2001
    Location
    USA
    Posts
    286
    Rep Power
    14
    What language are you using? Show us some example code.
    Jon Sagara

    "Me fail English? That's unpossible!"
  4. #3
  5. No Profile Picture
    PerlGuy
    Devshed Novice (500 - 999 posts)

    Join Date
    Jan 2001
    Posts
    720
    Rep Power
    42
    Language: C

    I thought the question was pretty clear but here:
    Code:
    main()
    {
        int a;    // not a problem
        
        // code
        // code
        // code
    
        int b;    // causes error
    }
    THere's no error though if I declare 'b' at the top of the main block(with 'a').
    - dsb -
    Perl Guy
  6. #4
  7. Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2001
    Location
    USA
    Posts
    286
    Rep Power
    14
    Yes, with C you have to declare your variables at the top of the code block. Not so with C++.
    Jon Sagara

    "Me fail English? That's unpossible!"
  8. #5
  9. No Profile Picture
    PerlGuy
    Devshed Novice (500 - 999 posts)

    Join Date
    Jan 2001
    Posts
    720
    Rep Power
    42
    Interesting.

    That's gonna be a tough habit to break, coming from Perl.
    - dsb -
    Perl Guy
  10. #6
  11. /(bb|[^b]{2})/

    Join Date
    Nov 2001
    Location
    Somewhere in the great unknown
    Posts
    5,163
    Rep Power
    793
    It isn't that you have to declare all variables at the beginning of the function, but you must declare it before you use it and be sure that you are declaring it in a block that it is being used in. You are always safer declaring it at the beginning of the function.

    A common mistake is this:
    Code:
    function foo(int a) {
        int b;
    
        if (a==1) {
            //another function call
            b = do_something(a);
            if (b == a) {
                int c;
                c = do_something(b);
            } else {
                c = do_something(a); //this is illegal, c doesn't exist here
            }
        }
    }

IMN logo majestic logo threadwatch logo seochat tools logo