|
|
|||||||||
|
|||||||||
| |||||||||
|
|
|
| |||||||||
![]() |
|
|
«
Previous Thread
|
Next Thread
»
|
Thread Tools | Search this Thread | Rate Thread | Display Modes |
|
#1
|
|||
|
|||
|
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
|
||||
|
||||
|
What language are you using? Show us some example code.
__________________
Jon Sagara "Me fail English? That's unpossible!" |
|
#3
|
|||
|
|||
|
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'). |
|
#4
|
||||
|
||||
|
Yes, with C you have to declare your variables at the top of the code block. Not so with C++.
|
|
#5
|
|||
|
|||
|
Interesting.
That's gonna be a tough habit to break, coming from Perl. |
|
#6
|
||||
|
||||
|
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
}
}
}
|
![]() |
| Viewing: Dev Shed Forums > Programming Languages > C Programming > Variable Declaration |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|
|
|