C++ Variables and User Input
September 11, 2018
In the last two tutorials, you learnt about C++ Data-types & Operators and Strings. In this tutorial, you’ll go into more depth about variables and how to get input from the user. Let’s get started!
Variables
Variables are used to store values. Variables are so central to programming that you’ll almost never come across which doesn’t use variables.
A good analogy for the variable is a box. You can imagine the name of the variable as the label on the box, and the value of the variable as what’s stored inside it.
Let’s create a new string variable called name
:
string name = "Commonlounge";
The above is equivalent to saying: Store the value "Commonlounge"
in variable name
.
So how do we know that the variable actually exists? Simply display the variable with cout
command:
cout << name << endl;
// Output - Commonlounge
Yippee! Your first variable! :)
Of course, variables can be anything – numbers too! Try this:
int n = 4;
cout << n << endl;
// Output - 4
The general syntax for declaring a variable is:
data_type variable_name = value;
Providing value when declaring a variable is optional. Some examples:
int age;
float weight = 110.60;
char gender = 'F';
Above, age
, weight
and gender
are variables of data-types integer, floating-point and character respectively.
We can also use more complicated expressions to assign a value to a variable. Here’s an example where we define two variables, and then store the result of their addition in a third variable:
int a = 30;
int b = 15;
int sum = a + b;
cout << sum << endl;
// Outputs - 45
Remember we said all expressions in C++ evaluate to a single value? The result of evaluating a variable is simply the value stored inside it. So, the step-by-step breakdown of evaluating expression a + b
above would be:
a + b
=> 30 + b <-- C++ looks up the value stored in variable "a"
=> 30 + 15 <-- C++ looks up the value stored in variable "b"
=> 45
You can always change the value stored inside the variable:
string name = "Commonlounge";
name = "David";
cout << name << endl;
// Output - David
Notice that we did
name = "David";
to change the value, notstring name = "David";
. The data-type (string
in this case) is required for declaring the variable, and we can only declare the variable once. If you declare the same variable multiple times, you get an error.
When you store a new value in a variable, the old value gets tossed out. This means we can’t get back to "Commonlounge"
again, unless we stored it in some other variable. For example:
string x = "Commonlounge";
string y = x;
cout << y << endl; // Output - Commonlounge
x = "David";
cout << x << endl; // Output - David
cout << y << endl; // Output - Commonlounge
Above, when we did y = x
, y
now has the value "Commonlounge"
inside it. Then we updated the value of x
to "David"
, but y
is unchanged.
You can also use a variable to assign value to itself.
string name = "Commonlounge";
name = "Hello " + name + "!";
cout << name << endl;
// Output - Hello Commonlounge!
When you do name = "Hello " + name + "!"
, you are telling C++ to evaluate the expression "Hello " + name + "!"
, and store the result in name
.
Here’s another example:
int a = 5;
a = a * 3;
cout << a << endl; // Output 15
a = a * a;
cout << a << endl; // Output 225
Awesome, right?
You can use variables in functions too:
string name = "David";
cout << name.length() <<endl;
// Output 5
Here’s the step-by-step breakdown of evaluating the above expression:
name.length()
=> "David".length() <-- C++ looks up the value stored in variable "name"
=> 5
But what if we used the wrong name? Can you guess what would happen? Let’s try!
string city = "Tokyo";
cout << ctiy << endl;
// error: 'ctiy' was not declared in this scope
An error! As you can see, C++ raises an error saying that the variable has not been declared, or in other words, that the variables doesn’t exist. If you encounter the not declared in this scope
error later, check your code to see if you’ve mistyped any names.
Play with this for a while and see what you can do!
Variable names
We can name a variable anything we want, such as age
, grade
, marks
etc. However, there are some restrictions:
- Can only contain alphanumeric characters and underscores (A-Z, 0-9, and ). For example,
name
,name2
, `mynameand
myName` are all allowed. - Must start with a letter or the underscore character. (it cannot start with a number). For example,
var
andvar3
are allowed, but2var
is not. - Is case-sensitive. For example,
age
andAGE
are two different variables.
Apart from these strict restrictions, here are some other guidelines that are helpful when choosing variable names:
- In general, people usually use snake case (examples -
var
,my_age
,favorite_number
) or camel case (examples -var
,myAge
,favoriteNumber
) when naming variables. - Descriptive variable names will make it easier to avoid mistakes, and easier to fix mistakes when you do make them. For example,
my_age
is a much better variable name thann
.
User Input
You’ve already learnt how to print values, but you haven’t yet learnt how to take input. Taking input from the user will allow us to write much more interesting programs.
To accept input from the user in C++, we use the cin
command, with the >>
operator. (The command is quite similar to cout
.) For example, here’s how to accept user input and store it in the number
variable:
int number;
cout << "Enter a number: ";
cin >> number;
cout << "The number is " << number;
To try out this code, follow this link.
Output:
Enter a number: 45
The number is 45
In the above interaction, the program outputted the prompt
Enter a number:
. Then, it waited for my input. I typed in45
and pressedEnter
. Finally, the program outputtedThe number is 45
.
cin
can also be chained (just like cout
) to accept more than one input value. For example:
int a, b;
cin >> a >> b;
cout << "The numbers you entered are " << a << " and " << b << endl;
To try out this code, follow this link.
Note, the program will keep waiting for input till the user enters two numbers.
Here’s a program that accepts two numbers as input and prints their sum:
#include <iostream>
using namespace std;
int main() {
int a, b;
cout << "Enter a number: "; // Output - "Enter a number: "
cin >> a; // You can input any integer, and it will get stored in a
cout << "Enter another number: "; // Output - "Enter another number: "
cin >> b; // Again, you can input any integer, and it will get stored in b
int sum = a + b; // sum of a and b will be stored in sum
cout << "Sum is: " << sum << endl; // Output - sum of a and b;
return 0;
}
To try out this code, follow <a href=”http://cpp.sh/77ojp” target=”blank”>this link._
Here’s what a sample interaction with the program looks like once you run it:
Enter a number: 18
Enter another number: 24
Sum is: 42
In the above interaction, I typed in 18 and 24. Everything else was outputted by the program.
Have fun with cin
command and use it with things that we have learnt so far. For example, try inputting strings!
Variable size in memory (and modifiers)
Apart from different data-types, like int
, float
, char
, etc, C++ has modifiers. Modifiers allow you to create a variable of a particular data-type, but with some differences.
Modifiers for int
For example, for the int
data-type, the following modifiers are available:
short w; // 2 bytes.
int x; // 4 bytes.
long y; // 4 bytes. (this modifier exists for historical reasons)
long long z; // 8 bytes.
Sizes mentioned above are true for most modern systems. Sizes may be different for really old computers.
As noted above, the different modifiers change how much space the variable takes in memory. Because of this, each of these have different limits on the minimum and maximum value the variable can store.
short int -32768 to +32767
int -2147483648 to +2147483647
long int -9223372036854775808 to +9223372036854775807
long long int -9223372036854775808 to +9223372036854775807
Here’s a simple program to demonstrate the difference:
#include <iostream>
using namespace std;
int main() {
int a = 1000000000;
int b = 2000000000;
cout << "int sum: " << a + b << endl;
long long int x = 1000000000LL; // LL stands for long long
long long int y = 2000000000LL;
cout << "long long int sum: " << x + y << endl;
return 0;
}
Output:
int sum: -1294967296
long long int sum: 3000000000
As you can see, the value 3 billion is too large to store in an int
. Hence, we get some gibberish as the result. This is called integer overflow. On the other hand, the same addition worked completely fine when we used long long int
.
We write
1000000000LL
instead of1000000000
, because by default some compilers consider integers written directly in the program to beint
. So, we useLL
when specifyinglong long
constants. Otherwise, integer overflow is going will happen even before the variable is assigned the initial value.
Modifiers for float
Similarly, for the float
data-type, the following modifiers are available:
float x; // 4 bytes
double y; // 8 bytes
long double z; // 8 bytes (this modifier exists for historical reasons)
The main difference between a float
and a double
is the number of digits of precision. A float
value is accurate to 6-7 significant digits, while double
values are accurate to 15-16 significant digits. Here’s a simple program to demonstrate the difference:
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
cout << setprecision(20);
float f = 3.141516287190842;
double d = 3.141516287190842;
cout << "float: " << f << endl;
cout << "double: " << d << endl;
cout << "float: " << 1000000.0*f << endl;
cout << "double: " << 1000000.0*d << endl;
return 0;
}
Output:
float: 3.1415162086486816406
double: 3.1415162871908419717
float: 3141516.2086486816406
double: 3141516.287190841922
As you can see, the float
variable has garbage digits after 8 significant digits, whereas double
variable has garbage digits after 15 significant digits.
The code above uses
setprecision(20)
which is a part ofiomanip
library to change the number of significant digits displayed to 20 digits.
Data-type sizes
The table below summarizes the minimum size for each of the C++ data-types:
bool: 1 bytes
char: 1 bytes
short: 2 bytes
int: 4 bytes
long: 4 bytes
long long: 8 bytes
float: 4 bytes
double: 8 bytes
long double: 8 bytes
You can also use the sizeof()
function to determine the size of a particular type or variable (in bytes). For example:
cout << "Size of bool is " << sizeof(bool) << " bytes";
// Output - Size of bool is 1 bytes
Similarly try to find the size of other data types yourself.
Conclusion
In this tutorial we learnt about:
- variables - used to store values
- asking the user for input - using the
cin
command - modifiers - which change the range of values that can be stored or the precision (for decimal values)
In the appendices below, we introduce assignment operations and increment / decrement operator. These operators are just shorthands for certain things that we need to do often in C++, i.e. they are not conceptually new things in C++. Rather, they make the code more concise.
Appendix: Assignment Operators
The simplest assignment operator we all know is =
operator. This assigns left hand side value to right hand side variable as we saw earlier.
int a = 42 ; // Here equals sign (=) assigns value 42 to variable a
cout << a << endl;
// Output 42
In addition to using the =
operator to assign a value to a variable, we also have operators like +=
, -=
, *=
, etc. Here’s how you can use these operators:
int x = 8;
x += 4; // equivalent to x = x + 4
cout << x << endl; // Output 12
x -= 2; // equivalent to x = x - 2
cout << x << endl; // Output 10
The same shorthand syntax applies to the multiplication, division, and modulus operators.
int x = 10;
x *= 3; // equivalent to x = x * 3
cout << x << endl; // Output 30
x /= 2; // equivalent to x = x / 2
cout << x << endl; // Output 15
x %= 4; // equivalent to x = x % 4
cout << x << endl; // Output 3
Appendix: Increment / Decrement Operator
There are some more shorthands that C++ provides. If you have an integer variable x
, you can do x++
, x--
, ++x
and --x
. These operators increase / decrease x
’s value by 1. That is:
x++; // equivalent to x = x + 1;
x--; // equivalent to x = x - 1;
For example:
int x = 11;
x++;
cout << x << endl;
// Outputs 12
What’s the difference between x++
(called postfix) and ++x
(called prefix)?
- Postfix first uses the value, and then increases it by 1.
- Prefix first increased the value by 1, and then uses the value.
So:
y = x++;
// equivalent to
// y = x; followed by
// x = x + 1;
y = ++x;
// equivalent to
// x = x + 1; followed by
// y = x;
For example:
int x = 5;
cout << ++x << endl; // Outputs 6
cout << x << endl; // Outputs 6
cout << x++ << endl; // Outputs 6 (value of x after this statement is 7)
cout << x << endl; // Outputs 7
See you in the next tutorial!