how can I use a particular variable name multiple times in a single program | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

how can I use a particular variable name multiple times in a single program

26th Jul 2016, 3:47 PM
Tara Prakash
6 Answers
+ 5
just write its name (without its type) when you need it...for example if i want to use the variable x=12 for many purposes i can write (in main): int x=12; int y=x*x; x=x+1; cout<<3*x+y; ------------------------ output: 183
26th Jul 2016, 4:19 PM
Abdorrahim tr
Abdorrahim tr - avatar
+ 3
ok...well you can't do that directly but here is something may help: you can use the keyword "namespace" to sort functions and variables in "namespaces"..and here,you can put more than two variables with the same name in different namespaces and then call the vatiables by the operator "::"..for example: #include <iostream> namespace tara{ int x=1; } namespace abdo{ int x=2; } int main() { std::cout<<tara::x<<endl; std::cout<<abdo::x; return 0; } -------------------------------------------------- outputs:1 2
26th Jul 2016, 8:30 PM
Abdorrahim tr
Abdorrahim tr - avatar
+ 1
int x, y, z;
26th Jul 2016, 7:54 PM
Muhammad Azam
Muhammad Azam - avatar
0
yes abdo17 is right about it
26th Jul 2016, 5:26 PM
Anirudh Gupta
Anirudh Gupta - avatar
0
My question was that can I store x= 1 & x =2 in the same program simultaneously
26th Jul 2016, 7:23 PM
Tara Prakash
0
A possible answer would be to use instance variables for objects you will learn about them in the classes section.
26th Jul 2016, 8:39 PM
Randall Nixon