+ 1
Shouldn't be the var name be defined before it's use? Please correct me if i am wrong.
14 Answers
+ 7
You are right. A variable should always be defined before its use, because the basic purpose of a variable is to hold a value for furthur use.
But if you are mis-interpreting the terms- variable definition and variable declaration, then read MrCoder's comment.
+ 7
No @MrCoder,
A variable cannot be declared twice in same scope.
Try your program in playground and check the result.
+ 7
0.o
@MrCoder,
you defined it first and declare it later?
I don't know about ruby but in C,C++, Java and PHP, rule is to declare first and then define or do both simultaneously.
+ 7
@MrCoder, That's what everyone do đ
Declare and define.
+ 6
@Supersebi3 Ohh... so thats why I get confused with JavaScript... you dont need to put a data type before the var name..
+ 6
@Supersebi3 Alright I got it, thanks :D
+ 5
Oh wait I meant I declared it and defined it laterđ
+ 5
@Sachin Artani I usually declare and define when making gamesđ
+ 5
@MrCoder the correct code would be
int main() {
string x;
//code
x = "A value is given";
cout << x;
return 0;
}
+ 5
@MrCoder only when declaring it
+ 4
Define is where you give a variable its value, However that variable name you mentioned was probably Declared which means it has no given value yet.
+ 4
Also you can Declare a variable first and declare them later:
(Thanks Sachin Artani :D)
#include <iostream>
using namespace std;
int main() {
int x;
//Some lines of code later...
int x = "A value is given";
cout << x;
}
+ 4
@Sachin Artani
Huh. Hhmm... I tried that on Ruby I defined it and declared it later. Maybe I was wrong or it is programming language dependent
0
I meant declare in the first place anyway guys. I just typed in define by mistake. Anyway, thank you guys for helping.