Shouldn't be the var name be defined before it's use? Please correct me if i am wrong. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Shouldn't be the var name be defined before it's use? Please correct me if i am wrong.

6th Apr 2017, 4:51 AM
Pranav Banerjee
Pranav Banerjee - avatar
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.
6th Apr 2017, 5:09 AM
Sachin Artani
Sachin Artani - avatar
+ 7
No @MrCoder, A variable cannot be declared twice in same scope. Try your program in playground and check the result.
6th Apr 2017, 5:16 AM
Sachin Artani
Sachin Artani - avatar
+ 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.
6th Apr 2017, 5:20 AM
Sachin Artani
Sachin Artani - avatar
+ 7
@MrCoder, That's what everyone do 😁 Declare and define.
6th Apr 2017, 5:29 AM
Sachin Artani
Sachin Artani - avatar
+ 6
@Supersebi3 Ohh... so thats why I get confused with JavaScript... you dont need to put a data type before the var name..
9th Apr 2017, 7:49 AM
MrCoder
MrCoder - avatar
+ 6
@Supersebi3 Alright I got it, thanks :D
9th Apr 2017, 7:51 AM
MrCoder
MrCoder - avatar
+ 5
Oh wait I meant I declared it and defined it later😂
6th Apr 2017, 5:21 AM
MrCoder
MrCoder - avatar
+ 5
@Sachin Artani I usually declare and define when making games😂
6th Apr 2017, 5:30 AM
MrCoder
MrCoder - avatar
+ 5
@MrCoder the correct code would be int main() { string x; //code x = "A value is given"; cout << x; return 0; }
9th Apr 2017, 7:47 AM
Supersebi3
Supersebi3 - avatar
+ 5
@MrCoder only when declaring it
9th Apr 2017, 7:50 AM
Supersebi3
Supersebi3 - avatar
+ 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.
6th Apr 2017, 5:01 AM
MrCoder
MrCoder - avatar
+ 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; }
6th Apr 2017, 5:12 AM
MrCoder
MrCoder - avatar
+ 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
6th Apr 2017, 5:18 AM
MrCoder
MrCoder - avatar
0
I meant declare in the first place anyway guys. I just typed in define by mistake. Anyway, thank you guys for helping.
5th May 2017, 3:32 PM
Pranav Banerjee
Pranav Banerjee - avatar