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.
You’ve entered the cout wrong and the x is not decreared
#include “stdafx.h”
#include
int main()
{
using namespace std;
int x; // decleares an integer callad x
x = 381645371355; // sets x to 381645371355
cout << x << endl; // read number in x
}
Yes, your code would work man! try this one, #include "stdafx.h" #include <iostream> //you have not included the library file.. int main() { using namespace std; int x; //i think you have to declare x.... cout << x; //then you can do whatever you like to... return 0; //not included... }You forgot to initialize x (ie. x = 7;)! I also think it is better if you put using namespace std; OUTSIDE main, to make it global.
I disagree. This can very easily in larger programs cause cryptic errors from name conflicts. Keeping using namespace within functions limits it’s scope, and thus limits its potential for causing problems. The safest, though, is to simply always refer to the namespaces, i.e. “std::cout << x” instead.
Is there any way that I can have two namespaces so that I could print two different places, within the same section of code?
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 ]
Try the following Kyle, it will surely work:
#include "stdafx.h" #include <iostream> int main() { using namespace std; cout << "Enter a number: "; //it will ask you to enter no.. int x; //declaring x as integer.. cin >> x; //asking the user for the value of x.. cout << "You have entered: " << x << endl; //displays your value and also ends the line return 0; }Ravi..
No, unfortunately it will not. His problem was that the program closed immediately after input. It is most likely because he has an IDE which breaks program execution immediately after main() returns 0. As such, he would need to either use a pause function such as system(”PAUSE”) to prompt the user to press enter, before the program breaks execution.
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 :(
Lol, which IDE and which OS are you using? Under Windows, you can use a function called system(”PAUSE”) in order to pause the program before it goes on (in your case, exits).
In your case, you then first need to write the following in the beginning of the program:
This will include the C standard library into your program.
Then, before the return statement in main(), add system(”PAUSE”), as such:
int main() { // Some code here... system("PAUSE"); return 0; }That should do it. However, the bad thing here is that I think this works ONLY on Windows…not good! Also, I have heard that the system() function is very unsafe and should generally be avoided in professional projects, which is perhaps not so important here because you are just studying.
Hope that helps! If you need more help you can mail me (csvanefalk@hushmail.me) or of course ask the owner of the site (Alex). Me and Alex are not affiliated in any way, I would just like to help out :) Dont forget to give the props to Alex for his great site though!
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).
This is feature of building debug C++ software with Visual Studio. Anything you don’t initialise yourself is set to 0xCCCCCCCC (interpreted as -858993460 if it’s an int).
Try switching the build type from debug to release, and the value will be truly uninitialised and may change each time you run it.
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 >.
Eeh I hate everyone who blame their OS for errors they commit themselves. It’s your own fault, not Vista’s.
Vista is an excellent OS, and stop saying otherwise =<_<=
Eeh I hate everyone who blame their OS for errors they commit themselves. It’s your own fault, not Vista’s; You should have learnt your IDE properly ya know?
Vista is an excellent OS, and stop saying otherwise =<_<=
Just add a pause at the bottom to see the result, such as:
hey i put down just what you typed. it paused and told me what i entered and then it exit is it spouse to do that.
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.
Try to use system() as small as possible. It will be better (in our situation) to use getch(); whicl allocated at conio.h
conio.h is not part of the C++ standard set of libraries, and is not included with all compilers. Consequently I would recommend avoiding its use whenever possible.
Would this work? thank you!
#include <iostream> using namespace std; int calculate() { int length; int width; int area; area = length * width; return 0; } int main() { cout << "hi and welcome to my rectangle area calculator" << endl; cout << "please enter the length of the rectangle:" << cin >> "length" <<; cout >> "thank you!" << endl; cout >> "please enter the width of the rectangle:" << endl; cin >> "width" <<; cout << "after a SPECTACULAR calculation the machine came up with the following answer:" << area << endl; return 0; }This is really the kind of thing that should go into the forums. If you want to repost it in the forum, I or another poster would be happy to address it there.
hey fluxx,
As soon as i saw your code i went at it trying to fix it. and to my pleasent suprize, i got it working.
here is the perfected code:
#include <iostream> int main() { using namespace std; cout << "Hi and welcome to my rectangle area calculator" << endl; cout << "please enter the length of the rectangle: "; int l; cin >> l; cout << "thank you" << endl; cout << "please enter the width of the rectangle: "; int w; cin >> w; cout << "after a SPECTACULAR calculation the machine came up with the following answer:" << l * w << endl; system ("pause"); return 0; }first of all, the whole “int caculate” part was compelely useless and unessary. second, “useing namespace std;” is suppost to be affter “int main ()”. third, many of your slash brackats are wrong, when useing cout, all slash brackets are facing the left . About the “system (”puase”)” part near the end, depending on what compiler you are useing you may not need it to be there. i’m useing a compiler that requires me to input a puase code. but even if your compiler dose not need it, it shoulden’t hurt anything.
Proof that ive actually learned something from this tutorial although in c I can make it so you can type booth the numbers on the same line but Im still learning both languages at the same time XD
#include <iostream> int main() { using namespace std; cout << "welcome to rectangle area calculator enter the first number: " ; int x ; cin >> x; cout << " enter the second number: " ; int b ; cin >> b ; int y; y = x * b; cout << "the area is: " << y << endl ; }I made this
#include "stdafx.h> #include <iostream> int main() { using namespace std; cout << "Enter a Number: " ; int x; cin >> x; cout << "This is The Number Multiplied by Two: "<< x * 2 << endl; return 0; }And it worked!!!
O_o
I suppose a kind compiler will accept that. Kind of… unconventional though. :)
Alex Sir,
I would like to know whenever i try to open a system file called “Pagefile.sys”
in the system directory C:\(in my case)… through C++..
It says “Access is Denied”.. Why??
And i would also like to know,
What are binary files?
What for, they are used?
What does the code in a Binary files signify?
There functionality..
Also,
a .DLL file is always linked with a .LIB file; why is it so?
Will be greatful for your precious comments on the above.
Your sincerely
Ravi Gaikwad
Student
India
This isn’t really on topic for this tutorial. Please repost this in the forums.
Hi alex i would like to ask you somthing when i put:
int x;
x = 5
it gives me this error 25 D:\Dev-Cpp\main.cpp expected constructor, destructor, or type conversion before ‘=’ token
and i am greatly confused plz help
Thankz
Justin
C++ learner
I don’t see anything wrong there, except that you don’t have a semicolon after x=5.
So, it is optimal to use the minimum amount of variables, when creating a program, to make it ‘light’ on resources (RAM)?
Nvm, stupid question. Sorry. Haha.
Only if you have a really huge number of variables (eg. in the thousands). Otherwise it won’t make much difference.
Hey Alex, great site you have here! I was taking a C++ class years ago, but as soon as we got to pointers I gave up. Since then, I have increased my knowledge a bit, at least with python / javascript, so I figured I would give C++ another go. Anyways, im learning a lot more here then I did in school, so thanks for the site!
Also, as far as pausing is concerned, I read this technique somewere -
#include "stdafx.h" #include <iostream> #include <conio.h> using namespace std; // Our custom built pause function static void pause() { cout << "Press any key to close this window..." << endl; _getch(); } int main() { cout << "Hellow World." << endl; pause(); // Call our custom pause function before close return 0; }They said their reasoning is it would be cross platform compilable, because pause.exe is windows specific, and also if someone / something were to tamper with pause.exe, executing pause.exe could be dangerous.
It seems to work well, what are your thoughts / opinions on it?
It’ll work in the majority of cases, and yes, it’s better than using pause.exe.
The only time it’ll fail is if there are extra characters in the input buffer — _getch() will read them and not stop for more input.
I present a slightly improved version of this in lesson 0.7 — a few common cpp problems that fixes that particular issue.
Sadly enough, the pausing issue is by far the most common topic on this site. :)
hi alex i just try this code and there is no problem just it gave me numbers instead of the name i have entered if you have any idea i’ll appreciate that
#include “stdafx.h” // Uncomment if Visual Studio user
#include
int main()
{
using namespace std;
cout <> x; // read number from console and store it in x
cout << “Thank you mr.” << x << endl;
return 0;
}
Jaber, you need to use cin for taking a value from the input and store it into x. You also have not defined x, so I dont understand how you managed to compile this program…and be careful with the << operator! :)
Your code should be something like this:
#include “stdafx.h” // Uncomment if Visual Studio user #include <string> using namespace std; int main() { string x; cin >> x; // read number from console and store it in x cout << “Thank you mr. ” << x << endl; return 0; }Some corrections here:
#include should be: #include
and string x; should be int x;
I dont know what I was thinking, sorry.
forgot pre tags… the include should be:
Which is the best C++ editor on Unbuntu
Code::Block is free and very simple to learn with like this tutorial says. Once you have more knowledge of c++ then you need to ask yourself a good questions. What platform will I be coding for? Windows, Linux, BSD, Phones, UFO’s etc..
If you mainly will be coding for he windows enviroment then Visual c++ from The makers of windows is a very logical choice but very expensive. Code::Block will still go a long way, infact it will do almost anything the other guy does but without all the bells and whisles and horse power thirst.
If you plan to code for Linux, then many choices come to you. QT4 is in my books one of the best platforms for GUI in the xorg world. Its now owned by nokia so alot more is to be expected from it. But I still mostly use Code::Block in linux for mostly anything from command line code to scripts and widgets. But when its time to build a GUI QT4 saves you alot of coding and trouble.
Hope this helps
Thank you who ever wrote this. Gave a very well explanation on wtf was going on. C is similar but cpp makes variables much simpler
Hi Alex, i am new to C++, please could you explain to me why you used the following lines:
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
as later you say that y=7 which it does …but if y=4 ..then y = 2 + 5 = 7
why did we have to use y = 4 ?
regards,
Jason
The idea was to show that if you re-assign a value to Y, then it will change.
Alex,
do this #include alone work?
y they r nt giving anything aftr tht?
what does #include alone mean?
Thanks
Alex, you are amazing. Thank you so much for writing these tutorials.
I’ve spent almost two hours reading (and re-reading until I made sure I understood what you are trying to say) chapter 1.3 and below. That might seem like a lot of time, but I want to know 100% what I’m doing.
I’m 14 years old and one day I’d love to work at a job having to do with programming (I’m looking at Valve Software right now). I knew nothing at all about C++, but very little Java, so I thought I should start here. Hopefully these tutorials will give me a good start, and I will continue to learn and practice C++ until I reach my goal. I understand that making games with C++ may be very different from what you’re teaching, but like I said, I’m hoping these tutorials will give me a good start.
Excuse my typing, it’s 2:40 AM and I’m a bit tired. I remembered what you mentioned at the beginning of the tutorial about being tired and/or unhappy.
Can’t wait for tomorrow!
system(”PAUSE”); after the Count entered number to keep it paused there.
Ok so if your values are assigned to a random memory address if we make the value just x then how will you find it?
On Fedora 12 using Netbeans 6.8, the code above dumps core:
/data/home/myusername/bin/netbeans-6.8/dlight2/bin/nativeexecution/dorun.sh: line 33: 32027 Illegal instruction (core dumped) sh “${SHFILE}”This is the exact code in the program (copied from the example in the lesson):
#include 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; }// math.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <iostream> main() { using namespace std; 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 */ }I keep getting an error message: error C4430: missing type specifier – int assumed. Note: C++ does not support default-int
and error C2065: ‘cout’ : undeclared identifier
and error C2065: ‘endl’ : undeclared identifier
I don’t know why the first one getting numbers worked fine but this one does not at all, all i tried to do was erase the old stuff and enter the new stuff.