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
The Code:
#include “stdafx.h”
#include
int main()
{
using namespace std;
cout > x; // read number from console and store it in x
cout
It Dosent Work
Lol, two things:
1) When posting code, use the PRE html tags or wordpress will eat it.
2) It works fine for me, and I just retested it in two different compilers. What compiler are you using, and what happens when you try to compile/run the code?
When you use the cout call from the output stream the directional indicator needs to be < .
The > is for the cin call from the library.
Use coutx.
When i try and run the code to enter a number and have it be displayed it isn’t working right. A box opens and it asks my number and i type it in and the box just closes. Not sure what im doing wrong.
[ Kyle, See this link -Alex ]
If you want the window to pause, use the following command:
system(”pause”);
It doesent Work.
When is Try it says
inter number here i enter the number and the Prg Closes :(
first the line looks wrong
it should be cout >> x; not cout > x;
Second, the prg closes if you are using VS2005 or a similar IDE. VS2005 creates a new console window when the program starts and closes it as soon as the program finishes. The code executed perfectly. Just that as soon as it prints the output, the program has finished and it closes leaving you no time to see it. you need to make it pause using a “cin” function.
i wrote my own terminating code:
it didn’t work when i tried it.
Timon, I addressed this issue in section 0.7
Where at? And the cause of the problem seems to be:
cin >> exitapp;
Answer 1 in section 0.7 talks about a method to keep the window open at the end of your program. Is that not what your issue is?
Ok. Thanks!
Why the value of -858993460 when displaying an uninitialized int?
It is not the min int. Is there a reason it is this value?
Thank you!
Memory is really just a sequence of binary bits strung together, and memory gets reused often. So your int variable x might use the same memory location as some other variable was using just a moment ago. If the variable x is not initialized, it “inherits” (in the non object-oriented sense) whatever value was there previously.
For example, let’s say there was 8 bits of memory that had this value: 0000 0101.
If you declared char chValue, and the variable chValue was assigned to this memory address, then chValue will start with the “uninitialized” value 5, because 0000 0101 binary = 5 decimal.
As a consequence of this, you never know what value an uninitialized variable will print because it depends on whatever happens to already be in memory the variable is using. It may change every time you run the program. It may change only occasionally. But you can always count on it being something you don’t want!
When i run that prog with uninitialized variable it keeps printing 2 every time…..
My question is same as Chucks. I tried this and it is printing -858993460 . Why is it printing a particular number if it is a garbage value? Is there a specific reason for that? I tried it 3-4 times and every time it prints -858993460 .
Thanks,
Renu
Because this variable is not allocated dynamically, it’s being allocated on the stack. Lots of stuff is put in the stack, including function call information, return addresses, etc… I presume (and this is just an educated guess) that the fact that we are all seeing the same number (-858993460) has something to do with the way the program or the OS is setting up the stack before the program begins executing. Perhaps the OS is cleaning out the stack to ensure that we don’t “recover” sensitive information from a prior program’s execution?
As an aside, although -858993460 seems like a really bizarre number, it’s actually just 0xCCCCCCCC in hex (which is bit pattern 1100 1100 1100 1100 1100 1100 1100 1100).
I got a little prob here:
when i run the program it asks me to enter a number and when i do and press enter, the program closes.. ?
(i use Dev-C++ 4.9.9.2)
Thx,
Me
See section 0.7, first answer.
hey, every time i run this code i keep getting 5 for the answer.
my guess is that its keeping x stored from the previous exercise, but shouldnt the cin.clear that you said to use get rid of that?
# include
int main ()
{
using namespace std;
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.
cin.clear();
cin.ignore(255, ‘\n’);
cin.get();
return 0;
}
Hi abdy. This program shouldn’t output anything since you don’t have any cout statements, so I am not sure how you “keep getting 5 for the answer”. If you are getting output, then I suspect you’re actually compiling and running a different project. Some compilers let you keep multiple projects open simultaneously. Make sure the project you want to compile is the active one (usually, right click on it and choose “set as active project” or something similar).
The cin.clear(); cin.ignore(255, ‘\n’); cin.get() lines just force the program to pause at the bottom so you can see the output before the window closes.
ehhh, i hate vista >.
Just add a pause at the bottom to see the result, such as:
Hello im a begginer with this program, and i have the problem that sometimes when i runing the program. It wont start it just says cant find file a error message.
Please tell me what the problem is!!
[ Please repost your code inside <pre></pre> tags, or even better, post it in the forums. -Alex ]
Whenever I try to compile the program that outputs the input variable…
#include "stdafx.h" // Uncomment this line if using Visual Studio #include int main() { using namespace std; cout <> x; // read number from console and store it in x cout << "You entered " << x << endl; return 0; }It gives me this error..
1>LINK : fatal error LNK1104: cannot open file ‘kernel32.lib’
Any ideas?
It sounds like your linker properties/directories are set up incorrectly.
You might see if this is your problem.
This needs to be more noob friendly. I don’t understand most of it, due to your obscure way of phrasing things. Please explain things so that normal people can understand.
>>Coconut
Maybe you should give an example of what you don’t understand instead of just pouting. People could then help you to understand.
#include <iostream>
using namespace std;
int main(void)
{
cout << "Enter a number: " << endl;
int x;
cin >> x;
cout << "You entered " << x << endl;
system ("pause");
return 0;
}
You cuold have probably went into a little more detail about those 2 functions but you did a good job of getting us on the right track…to start with.