Variables

How come I can change the integer given to the specific variable, the given integer is not permenant for one variable?

For example:
int x;
x = 0;
cout << "My Number Is?";
cout << x;
cout << endl;

Below:

x = 2;
cout << "My Number Is?";
cout << x;
use const for constant variables...
I think I understand your question but I'm not completely sure, so if this answer is not right for what you are asking maybe you could ask it a different way.

When you declare a variable you are actually naming a location in memory, and you can think of it as a box into which you can place different values.

1
2
3
int x; //Name of a memory location
x=0;//Place a 0 in the location named x.
x=2;//Changes the value in that location to 2. 


So you can change the value in the variable at any point using the assignment operator (=).

If you want a place to store a value which can not be changed you must use a constant.

 
const int X=0;//The compiler will not let you change this value during the program. 


Typically constants are declared with uppercase letters to make the code more readable.

Hope this was helpful.

Edit: Beat me to it. =P
Last edited on
So, if I use "const", the statement variable will be set to a integer of my choice permanently and cannot be changed?

I also have another question: How do I make it so that in the cmd screen, the person can continuously enter their value without it closing?

For example:
1
2
3
4
5
6
int test;
cout << "Please Choose A Number And Enter It";
cin >> test;
cout << "Your New Number Is.....";
test = test + 20;
cout << test << endl;


I want the user to be able to continuously enter values into the command shell without it closing.
I want the user to be able to continuously enter values into the command shell without it closing.

Put your code into while loop
1
2
3
4
5
6
7
8
9
int test;
cout << "Please Choose A Number And Enter It ";
while(cin >>test) // quit while loop if cin fails
  {
    cout << "Your New Number Is.....";
    test = test + 20;
    cout << test << endl;
    cout << "Please Choose A Number And Enter It";
  }
Last edited on
The easiest way would be to use a do-while loop. You will need something that the user can enter to kick it out of the loop when they want to quit. There are many ways to do this, but here is an example where the user enters 99 when they want to quit.

1
2
3
4
5
6
7
8
9
int test;
do 
{
	cout << "Please Choose A Number And Enter It, Or Enter 99 to Quit.\n";
	cin >> test;
	cout << "Your New Number Is.....";
	test = test + 20;
	cout << test << endl;
}while(test!=119);//119 is 99+20 


Edit: Beat again!! lol
Last edited on
Topic archived. No new replies allowed.