A statement

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.

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):

1
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:

1
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:

1
2
3
4
5
6
7
8
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:

1
2
3
4
5
6
7
8
9
10
11
// #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:

1
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:

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.

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.

1
2
3
4
5
6
7
8
9
10
11
12
//#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?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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) Show Solution

2) Show Solution

3) Show Solution

4) Show Solution

5) Show Solution

 1.4 — A first look at functions
 Index
 1.2 — Comments

160 comments to 1.3 — A first look at variables (and cin)

  • EViL

    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.

  • JLaughters

    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;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值