Variables
A statement such as x = 5 seems obvious enough. As you would guess, we are assigning the value of 5 to x. But what exactly is x? x is a variable.
A variable in C++ is a name for a piece of memory that can be used to store information. You can think of a variable as a mailbox, or a cubbyhole, where we can put and retrieve information. All computers have memory, called RAM (random access memory), that is available for programs to use. When a variable is declared, a piece of that memory is set aside for that variable.
In this section, we are only going to consider integer variables. An integer is a whole number, such as 1, 2, 3, -1, -12, or 16. An integer variable is a variable that can only hold an integer value.
In order to declare a variable, we generally use a declaration statement. Here’s an example of declaring variable x as an integer variable (one that can hold integer values):
int x;
When this statement is executed by the CPU, a piece of memory from RAM will be set aside. For the sake of example, let’s say that the variable x is assigned memory location 140. Whenever the program sees the value x in an expression or statement, it knows that it should look in memory location 140.
One of the most common operations done with variables is assignment. To do this, we use the assignment operator, more commonly known as equals, more commonly known as the = symbol. When the CPU executes a statement such as x = 5;, it translates this to “put the value of 5 in memory location 140″.
Later in our program, we could print that value to the screen using cout:
cout << x; // prints the value of x (memory location 140) to the console
In C++, variables are also known as l-values (pronounced ell-values). An l-value is a value that has an address (in memory). Since all variables have addresses, all variables are l-values. They were originally named l-values because they are the only values that can be on the left side of an assignment statement. When we do an assignment, the left hand side of the assignment operator must be an l-value. Consequently, a statement like 5 = 6; will cause a compile error, because 5 is not an l-value. The value of 5 has no memory, and thus nothing can be assigned to it. 5 means 5, and it’s value can not be reassigned. When an l-value has a value assigned to it, the current value is overwritten.
The opposite of l-values are r-values. An r-value refers to any value that can be assigned to an l-value. r-values are always evaluated to produce a single value. Examples of r-values are single numbers (such as 5, which evaluates to 5), variables (such as x, which evaluates to whatever number was last assigned to it), or expressions (such as 2+x, which evaluates to the last value of x plus 2).
Here is an example of some assignment statements, showing how the r-values evaluate:
int y; // declare y as an integer variable y = 4; // 4 evaluates to 4, which is then assigned to y y = 2 + 5; // 2 + 5 evaluates to 7, which is then assigned to y int x; // declare x as an integer variable x = y; // y evaluates to 7, which is then assigned to x. x = x; // x evaluates to 7, which is then assigned to x (useless!) x = x + 1; // x + 1 evaluates to 8, which is then assigned to x.
There are two important things to note. First, there is no guarantee that your variables will be assigned the same memory address each time your program is run. The first time you run your program, x may be assigned to memory location 140. The second time, it may be assigned to memory location 168. Second, when a variable is assigned to a memory location, the value in that memory location is undefined (in other words, whatever value was there last is still there).
This can lead to interesting (and by interesting, we mean dangerous) results. Consider the following short program:
// #include "stdafx.h" // Uncomment if Visual Studio user
#include <iostream>
int main()
{
using namespace std; // gives us access to cout and endl
int x; // declare an integer variable named x
// print the value of x to the screen (dangerous, because x is uninitialized)
cout << x << endl;
}
In this case, the computer will assign some unused memory to x. It will then send the value residing in that memory location to cout, which will print the value. But what value will it print? The answer is “who knows!”. You can try running this program in your compiler and see what value it prints. To give you an example, when we ran this program with an older version of the Visual Studio compiler, cout printed the value -858993460. Some newer compilers, such as Visual Studio 2005 Express will pop up a debug error message if you run this program from within the IDE.
A variable that has not been assigned a value is called an uninitialized variable. Uninitialized variables are very dangerous because they cause intermittent problems (due to having different values each time you run the program). This can make them very hard to debug. Most modern compilers will print warnings at compile-time if they can detect a variable that is used without being initialized. For example, compiling the above program on Visual Studio 2005 express produced the following warning:
c:\vc2005projects\test\test\test.cpp(11) : warning C4700: uninitialized local variable 'x' used
A good rule is to always assign values to variables when they are declared. C++ makes this easy by letting you assign values on the same line as the declaration of the variable:
int x = 0; // declare integer variable x and assign the value of 0 to it.
This ensures that your variable will always have a consistent value, making it easier to debug if something goes wrong somewhere else.
One common trick that experienced programmers use is to assign the variable an initial value that is outside the range of meaningful values for that variable. For example, if we had a variable to store the number of cats the old lady down the street has, we might do the following:
int cats = -1;
Having -1 cats makes no sense. So if later, we did this:
cout << cats << " cats" << endl;
and it printed “-1 cats”, we know that the variable was never assigned a real value correctly.
Rule: Always assign values to your variables when you declare them.
We will discuss variables in more detail in an upcoming section.
cin
cin is the opposite of cout: whereas cout prints data to the console, cin reads data from the console. Now that you have a basic understanding of variables, we can use cin to get input from the user and store it in a variable.
//#include "stdafx.h" // Uncomment this line if using Visual Studio
#include <iostream>
int main()
{
using namespace std;
cout << "Enter a number: "; // ask user for a number
int x;
cin >> x; // read number from console and store it in x
cout << "You entered " << x << endl;
return 0;
}
Try compiling this program and running it for yourself. When you run the program, it will print “Enter a number: ” and then wait for you to enter one. Once you enter a number (and press enter), it will print “You entered ” followed by the number you just entered.
This is an easy way to get input from the user, and we will use it in many of our examples going forward.
Quiz
What values does this program print?
int x = 5; x = x - 2; cout << x << endl; // #1 int y = x; cout << y << endl; // #2 // x + y is an r-value in this context, so evaluate their values cout << x + y << endl; // #3 cout << x << endl; // #4 int z; cout << z << endl; // #5
Quiz Answers
To see these answers, select the area below with your mouse.
1.4 — A first look at functions
|
Index
|
1.2 — Comments
|
1.4 — A first look at functions
Index
1.2 — Comments
Help a no0b with this code:
#include "stdafx.h" #include <iostream> void add() { using namespace std; cout << "Result: " << x + y << endl; } int main() { using namespace std; cout << "Type 1st number..." << endl; int x; cin >> x; cout << "Type 2nd number..." << endl; int y; cin >> y; add(); return 0; }Thanks.
ok. i found the answer in the next chapter. :)
When I run this program it looks like I input a number and always get output of 0.
It should take the user input in function input1 and save it to variable a. Then return a to main to be cout. I added a cout in input1 after the user input to see if the user’s inputs was being stored as a. It was. It seems though that when a is returned to main a is being reset to 0.
#include "stdafx.h" #include <iostream> int input1(int a) { using namespace std; cin >> a; return a; } int main() { using namespace std; int a = 0; input1(a); cout << a; return 0; }you are printing the local copy of ‘a’ and not the return value. The local copy of ‘a’ is initialized to 0 and not changed anywhere in the main. hence 0 is displayed.
solution:
update the local copy of ‘a’ with the return value.
a = input1(a);
cout << a;
Okay, I’m having some problems, I’m using Code::Block and using the ‘consle application’. So this is what I put in:
1//#include “stdafx.h”
2#include
3
4int main()
5{
6 using namespace std;
7 cout <> x; // read number from console and store it in x
10 cout << "You entered " << x << endl;
11 return 0;
12}
And this is what the result was for the build:
Line Message
2 error: iostream: No such file or directory
In function 'main':
6 error: 'using' undeclared (first use in this function)
6 error:(Each undeclared identifier is reported only once for each function it appears in.)
6 error: expected ';' before 'namespace'
7 error: 'cout' undeclared (first use in this function)
9 error: 'cin' undeclared (first use in this function)
10 error: 'endl' undeclared (first use in this function)
=== Build finished: 8 errors, 0 warnings===
Also, every time I 'try' running it (even though it really is not a good idea) it appears as the 'HelloWorld' thing from a few lessons ago. I would really appreciate it if some could help me and tell me what I did wrong?
you deleted from Line 2. Should’ve been #include shouldn’t it?
I meant iostream.
you deleted from Line 2 iostream. I wrote “Should’ve been #include iostream shouldn’t it?”
this comment pad deletes texts inside the brackets! :O)
I just wanted to say this is a really great tutorial. I’m learning c++ for my 2nd day and have created this program:
#include “stdafx.h” // Uncomment this line if using Visual Studio
#include
int main()
{
int x, y, f, d;
x = 10;
y = 20;
f = x + y;
d = y + f;
using namespace std;
char userInput;
cout <> userInput;
cin.ignore();
if (userInput == ‘x’) {
cout << "You have chosen number " << x << endl;
}
else if (userInput == 'y') {
cout << "You have chosen number " << y << endl;
}
else if (userInput == 'f') {
cout << "You have chosen number " << f << endl;
}
else if (userInput == 'd') {
cout << "You have chosen number " << d << endl;
}
cin.get();
return 0;
}
There are still a few questions I have, like if the user inputs a letter different than the 4 listed, if there is a shortcut way to say "any", or would I have to use every other character with a million "else if statements". But I'm sure this question will be answered as I keep going through the tutorials. Also about coloring text, not sure how to do it but I'm sure this will also be answered later on.
weird line 13 pasted differently than I have it. anyway its:
cout << "Please choose the letter x, y, f, or d: ";
you must do a
elseafter the lastelse if (userInput == 'd') {cout << "You have chosen number " << d << endl;showing a error message like:cerr << "wrong letter, try again.";that way, in case of the user not entering the right letter the program will give that message.These tutorials are extremely helpful.
Thank you very much.
However there is no mention of the different Data Types. You have mentioned them just once in the Chapter Variable & size of operator.
I find these at CPlusPlus.com Variables. Data Types
Can you explain these in details?
This is explained in later sections of the tutorial.
What does the l in l-value and the r in r-value stand for? right and left?
…also I don’t get how I can go as far as to copy the thing I was supposed to do exactly and there are build errors or something. It seem to do the exact same thing the last program did…
…what does cout stand for? what does cin stand for? why is << sometimes facing one way and sometimes facing another without an obvious reason?
1) Yes, r-value stands for right value, and l-value stands for left value.
2) What errors are you talking about? Did you copy only the code without the line numbers? did you remove the VS part?
It’s quite possible that the author had some typos, but it might be a problem on your end too.
3) c – standard (don’t ask me), out – output, in – input. As for ‘>>’ and ‘<<' – I can't really explain why is that.
my interpretation of >> and < keyboard
standard output device => monitor
consider variable x and following scenarios
we need to store the value from keyboard to variable x
cin >> x; visualize like keyboard >> x
we need to display value x onto monitor
cout << x; visualize like monitor << x
here according to me arrows indicate data flow.
if anyone else have any other interpretation, then you can addon or correct me.
some problem in the html tag so re posting.
according to my interpretation, the standard io stream is used in the code.
for the standard stream
standard input device => keyboard
standard output device => monitor
consider variable x and following scenarios
we need to store the value from keyboard to variable x
cin >> x; visualize like keyboard >> x
we need to display value x onto monitor
cout << x; visualize like monitor << x
here according to me arrows indicate data flow.
if anyone else have any other interpretation, then you can addon or correct me.
Hi after several attempts of my program not running after question # 1 on the quiz I finally got it to run by using:
#include "stdafx.h"#include <iostream>
int main()
{
using namespace std;
int x = 5;
x = x - 2;
cout << x << endl; //#1
cin.clear ();
cin.ignore(255, '\n');
cin.get ();
int y = x;
cout << y << endl; //#2
cin.clear ();
cin.ignore(255, '\n');
cin.get ();
cout << x + y << endl; //#3
cin.clear ();
cin.ignore(255, '\n');
cin.get ();
cout << x << endl; //#4
cin.clear ();
cin.ignore(255, '\n');
cin.get ();
int z;
cout << z << endl; //#5
cin.clear ();
cin.ignore(255, '\n');
cin.get ();
return 0;
}
Q: why does declaring a variable using
int (A);
work the same as
int A;
??? should there be a difference between the two declaration statements, esp given that the variable name is enclosed in brackets?
I don’t think that there’s a difference, no. Still, enclosing a variable name in brackets looks kind of silly and is redundant.
I got the number 2
I am so glad to find your website. There is a very logical rationale behind your explanation which makes it simpler and at the same time joyful to learn.
Many thanks for all the hard and smart work.
when i compiled the program that uses the cin cout. i enter the number then press enter and suddenly the program closes. and this is the code i compiled.please tell me if there is anything wrong with it. (im using code blocks but on windows)
#include
int main()
{
using namespace std;
cout<>x;
cout<< "You Entered"<< x <<endl;
return 0;
}
That’s because there’s nothing that prevents the program from closing after the cout runs. IIRC Code::Blocks had a bug which would sometimes bug out the thing that’s responsible for keeping the window up once the code has been executed (cin related too, I think).
Just put a cin.ignore().get(); after the cout line.
[...] This lesson builds directly on the material in the section “A first look at variables“. [...]
[...] This lesson builds directly on the material in the section “A first look at variables“. [...]
#include int variables () { using namespace std; cout <> b; int e; e = b*10; int l; l = e/100; int a; a = e+b; int d; d = l+e; int s; s = 2*(d-a); int m; m = b+l; cout << b << e << l << a << d << s << m; return 0; } 1>------ Build started: Project: Hell, Configuration: Debug Win32 ------ 1> variables.cpp 1> LINK : C:\Users\Administrator\Documents\Visual Studio 2010\Projects\Hell\Debug\Hell.exe not found or not built by the last incremental link; performing full link 1>LINK : fatal error LNK1561: entry point must be defined ========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ========== Umm... okay, im sure there is a coding problem on my end, but what?yes i do have #include iosteam in there with its normal pointy thingys.
i give i cant get a proper post in
#include
int variables ()
{
using namespace std;
cout <> b;
int e;
e = b*10;
int l;
l = e/100;
int a;
a = e+b;
int d;
d = l+e;
int s;
s = 2*(d-a);
int m;
m = b+l;
cout << b << e << l << a << d << s << m;
return 0;
}
#include <iostream>
int variables ()
{
using namespace std;
cout << "Enter a Number: ";
int b;
cin >> b;
int e;
e = b*10;
int l;
l = e/100;
int a;
a = e+b;
int d;
d = l+e;
int s;
s = 2*(d-a);
int m;
m = b+l;
cout << b << e << l << a << d << s << m;
return 0;
}
there thats what your looking at
1>—— Build started: Project: Hell, Configuration: Debug Win32 ——
1> variables.cpp
1> LINK : C:\Users\Administrator\Documents\Visual Studio 2010\Projects\Hell\Debug\Hell.exe not found or not built by the last incremental link; performing full link
1>LINK : fatal error LNK1561: entry point must be defined
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
Umm… okay, im sure there is a coding problem on my end, but what?
#include
int variables ()
{
using namespace std;
cout <> b;
int e;
e = b*10;
int l;
l = e/100;
int a;
a = e+b;
int d;
d = l+e;
int s;
s = 2*(d-a);
int m;
m = b+l;
cout << b << e << l << a << d << s << m;
return 0;
}
you are missing main() function. Updated code is
#include “stdafx.h”
#include
int main()
{
using namespace std;
cout <> b;
int e;
e = b*10;
int l;
l = e/100;
int a;
a = e+b;
int d;
d = l+e;
int s;
s = 2*(d-a);
int m;
m = b+l;
cout << b << e << l << a << d << s << m;
return 0;
}
[...] This lesson builds directly on the material in the section “A first look at variables“. [...]
Here’s one I made. I didn’t really look at this too much but I use my knowledge from java here:
#include <iostream> // tells compiler what cout and endl do
double num; // declare variables
double num1; // double means you can use decimals!
int main() // program runs main
{
using namespace std; // make life easier, instead of std::cout and std::endl
cout << "Welcome to my calculator! \n" << endl; // displays welcome!
cout << "Please enter your first number:" << endl; // tells user to enter num
cin >> num; // lets person enter num and stores it into num
cout << "Please enter your second number:" << endl; // tells user to enter num1
cin >> num1; // lets person enter num1 and stores it into num1
cout << "The result is: " << num + num1 << endl; // Add num + num1
system("pause"); // Pauses the cmd from closing.
return 0; // return nothing
}
why is main() function preceded by int ? my reference books show the use of void. does it make any difference?
“One common trick that experienced programmers use is to assign the variable an initial value that is outside the range of meaningful values for that variable. For example, if we had a variable to store the number of cats the old lady down the street has, we might do the following:
1
int cats = -1;
Having -1 cats makes no sense. So if later, we did this:
1
cout << cats << " cats" << endl;
and it printed “-1 cats”, we know that the variable was never assigned a real value correctly."
Could anyone help explain this to me? I seriously need help on this. Talk to me… like a 10 year old if you can :D
i shall give a try to answer this question.
first of all, when you print the value of cats in hex, you will find a probable answer. you can use following method.
int cats = -1;
cout << "value in hex =" << hex << cats;
the program should give result as 0xFFFFFFFF(4294967295)
so here we can understand that cats is assigned with the largest value that can be stored in an integer variable.
normally in a user code, we dont use such a huge value to model real life problems/numeric.
More over we need to assign a variable with an initial value which may not be used further in the program. And to start with, what better than the largest value?
if my interpretation is wrong, others can correct or add suggestions.
adding usecase for above explanation
if variable “choice” is not initialised at the beginning,
please observe the else case is required to distinguish the choice value.
int choice;
if (fruit is “mango”)
{
choice = 0;
}
else if (fruit is “banana”)
{
choice = 1;
}
else if (fruit is “apple”)
{
choice = 2;
}
else
{
choice = 3;
// here 3 can be used to indicate “no fruit selected”
// and may be used further below in the code.
// say later another fruit is added, then the value 3,
// needs to be changed everywhere in the code
}
if choice is initialised at the beginning, then the last else is not required
int choice = -1;
if (fruit is “mango”)
{
choice = 0;
}
else if (fruit is “banana”)
{
choice = 1;
}
else if (fruit is “apple”)
{
choice = 2;
}
// here else case is not required and choice is interpreted as -1
// -1 is not a frequently used value. hence can be chosen for unused(default) values.
[...] 1) Show Solution [...]
Ok, so I tried the program on this page, but I keep getting the X value +3. Does anyone know what I am doing wrong here?
#include
int main ()
{
using namespace std;
cout <> x;
cout << "You entered " << x << endl;
return 0;
}
Your main function should be:
int main ()
{
// what you want for code before the program
float x; // float can handle just about any size number
//(unlike int)
cout <> x;
cout << "\nYou entered " << x << endl;
return EXIT_SUCCESS;
}
I double checked everything, there are NO typing errors.”\n” is the “slash combination” to make a new line in
cout.
string y;
Cin >> y;
is
not
valid code because cin does
not
accept “string” variables.
#include
int main()
{
std::cout <> x;
std::cout << "You entered" << x <—— Build started: Project: Enter Integer001.cpp, Configuration: Debug Win32 ——
1> Enter Integer001.cpp
1>c:\users\mike\documents\c++ programs\enter integer001.cpp\enter integer001.cpp\enter integer001.cpp(8): error C2065: ‘endl’ : undeclared identifier
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
I am running Windows 7 with Microsoft Visual C++ 2010 Express
Can anyone help? I don’t know why I am getting that error message.
#include
int main()
{
std::cout <> x;
std::cout << "You entered" << x << endl;
return 0;
}
When I run this program I get the following error message: error c2065: 'endl' : undeclared indentifier
I am running Windows 7 with Microsoft Visual C++ 2010 Express IDE
Can anyone help me? I don't know why I am getting this error message.
i m new,can u help me out!!! the input statement is not returning value to variable z,y???
#include “stdafx.h”
#include
int input1()
{
using namespace std;
cout<> x;
return x;
}
int main()
{
using namespace std;
int z= input1();
cout << z;
return 0;
}
sorry i got my mistake
how to run your program without using microsoft visual C++ ?