Learning C++ Part One Example

C++ Syntax

Example

  1. #include <iostream>
  2. using namespace std;

  3. int main() {
  4.   cout << "Hello World!";
  5.   return 0;
  6. }

Example explained

  • Line 1: #include <iostream> is a header file library that lets us work with input and output objects, such as cout (used in line 5). Header files add functionality to C++ programs.
  • Line 2: using namespace std means that we can use names for objects and variables from the standard library.
  • Line 3: A blank line. C++ ignores white space. But we use it to make the code more readable.
  • Line 4: Another thing that always appear in a C++ program, is int main(). This is called a function. Any code inside its curly brackets {} will be executed.
  • Line 5: cout (pronounced "see-out") is an object used together with the insertion operator (<<) to output/print text. In our example it will output "Hello World!".
  • Note: Every C++ statement ends with a semicolon;.
  • Note: The body of int main() could also been written as:
  • int main () { cout << "Hello World! "; return 0; }
  • Remember: The compiler ignores white spaces. However, multiple lines makes the code more readable.
  • Line 6: return 0 ends the main function.
  • Line 7: Do not forget to add the closing curly bracket } to actually end the main function.

Omitting Namespace

You might see some C++ programs that runs without the standard namespace library. The using namespace std line can be omitted and replaced with the std keyword, followed by the:: operator for some objects:

Example

  1. #include <iostream>

  2. int main() {
  3.   std::cout << "Hello World!";
  4.   return 0;
  5. }

C++ Output (Print Text)

The cout object, together with the << operator, is used to output values/print text:

Example
  1. #include <iostream>
  2. using namespace std;

  3. int main() {
  4.   cout << "Hello World!";
  5.   return 0;
  6. }
Example
  1. #include <iostream>
  2. using namespace std;

  3. int main() {
  4.   cout << "Hello World!";
  5.   cout << "I am learning C++";
  6.   return 0;
  7. }
New Lines
To insert a new line, you can use the \n character:

Example
  1. #include <iostream>
  2. using namespace std;

  3. int main() {
  4.   cout << "Hello World! \n";
  5.   cout << "I am learning C++";
  6.   return 0;
  7. }
Tip: Two \n characters after each other will create a blank line:

Example
  1. #include <iostream>
  2. using namespace std;

  3. int main() {
  4.   cout << "Hello World! \n\n";
  5.   cout << "I am learning C++";
  6.   return 0;
  7. }
Another way to insert a new line, is with the endl manipulator:

Example
  1. #include <iostream>
  2. using namespace std;

  3. int main() {
  4.   cout << "Hello World!" << endl;
  5.   cout << "I am learning C++";
  6.   return 0;
  7. }

Both \n and endl are used to break lines. However, \n is the most used.

But what is \n exactly?
The newline character (\n) is called an escape sequence, and it forces the cursor to change its position to the beginning of the next line on the screen. This results in a new line.

Examples of other valid escape sequences are:

Escape Sequence

Description

\t

Creates a horizontal tab

\\

Inserts a backslash character (\)

\"

Inserts a double quote character


C++ Comments
Comments can be used to explain C++ code, and to make it more readable. It can also be used to prevent execution when testing alternative code. Comments can be singled-lined or multi-lined.

Single-line Comments
Single-line comments start with two forward slashes (//).

Any text between // and the end of the line is ignored by the compiler (will not be executed).

This example uses a single-line comment before a line of code:

Example
  1. // This is a comment
  2. cout << "Hello World!";
Example
  1. cout << "Hello World!"; // This is a comment
C++ Multi-line Comments
Multi-line comments start with /* and ends with */.

Any text between /* and */ will be ignored by the compiler:

Example
  1. /* The code below will print the words Hello World!
  2. to the screen, and it is amazing */
  3. cout << "Hello World!";

Single or multi-line comments?
It is up to you which you want to use. Normally, we use // for short comments, and /* */ for longer.


C++ Variables

Variables are containers for storing data values.

In C++, there are different types of variables (defined with different keywords), for example:

  • int - stores integers (whole numbers), without decimals, such as 123 or -123
  • double - stores floating point numbers, with decimals, such as 19.99 or -19.99
  • char - stores single characters, such as 'a' or 'B'. Char values are surrounded by single quotes
  • string - stores text, such as "Hello World". String values are surrounded by double quotes
  • bool - stores values with two states: true or false

Declaring (Creating) Variables

To create a variable, specify the type and assign it a value:

Syntax
  1. type variableName = value;
Where type is one of C++ types (such as int), and variableName is the name of the variable (such as x or myName). The equal sign is used to assign values to the variable.

To create a variable that should store a number, look at the following example:

Example
Create a variable called myNum of type int and assign it the value 15:

  1. int myNum = 15;
  2. cout << myNum;

You can also declare a variable without assigning the value, and assign the value later:

Example
  1. int myNum;
  2. myNum = 15;
  3. cout << myNum;

Note that if you assign a new value to an existing variable, it will overwrite the previous value:

Example
  1. int myNum = 15;  // myNum is 15
  2. myNum = 10;  // Now myNum is 10
  3. cout << myNum;  // Outputs 10

Other Types

A demonstration of other data types:

Example
  1. int myNum = 5;               // Integer (whole number without decimals)
  2. double myFloatNum = 5.99;    // Floating point number (with decimals)
  3. char myLetter = 'D';         // Character
  4. string myText = "Hello";     // String (text)
  5. bool myBoolean = true;       // Boolean (true or false)
You will learn more about the individual types in the Data Types chapter.

Display Variables

The cout object is used together with the << operator to display variables.

To combine both text and a variable, separate them with the << operator:

Example
  1. int myAge = 35;
  2. cout << "I am " << myAge << " years old.";

Add Variables Together

To add a variable to another variable, you can use the + operator:

Example
  1. int x = 5;
  2. int y = 6;
  3. int sum = x + y;
  4. cout << sum;
C++ Exercises
Test Yourself With Exercises
Exercise:
Create a variable named myNum and assign the value 50 to it.

Declare Many Variables

To declare more than one variable of the same type, use a comma-separated list:

Example
  1. int x = 5, y = 6, z = 50;
  2. cout << x + y + z;

One Value to Multiple Variables
You can also assign the same value to multiple variables in one line:

Example
  1. int x, y, z;
  2. x = y = z = 50;
  3. cout << x + y + z;

C++ Identifiers

All C++ variables must be identified with unique names.

These unique names are called identifiers.

Identifiers can be short names (like x and y) or more descriptive names (age, sum, total volume).

Note: It is recommended to use descriptive names in order to create understandable and maintainable code:

Example
  1. // Good
  2. int minutesPerHour = 60;

  3. // OK, but not so easy to understand what m actually is
  4. int m = 60;
The general rules for naming variables are:

  • Names can contain letters, digits and underscores
  • Names must begin with a letter or an underscore (_)
  • Names are case sensitive (myVar and myvar are different variables)
  • Names cannot contain whitespaces or special characters like !, #, %, etc.
  • Reserved words (like C++ keywords, such as int) cannot be used as names

Constants

When you do not want others (or yourself) to change existing variable values, use the const keyword (this will declare the variable as "constant", which means unchangeable and read-only):

Example
  1. const int myNum = 15;  // myNum will always be 15
  2. myNum = 10;  // error: assignment of read-only variable 'myNum'
You should always declare the variable as constant when you have values that are unlikely to change:

Example
  1. const int minutesPerHour = 60;
  2. const float PI = 3.14;

C++ User Input

You have already learned that cout is used to output (print) values. Now we will use cin to get user input.

cin is a predefined variable that reads data from the keyboard with the extraction operator (>>).

In the following example, the user can input a number, which is stored in the variable x. Then we print the value of x:

Example
  1. int x; 
  2. cout << "Type a number: "; // Type a number and press enter
  3. cin >> x; // Get user input from the keyboard
  4. cout << "Your number is: " << x; // Display the input value
Good To Know
  • cout is pronounced "see-out". Used for output, and uses the insertion operator (<<)
  • cin is pronounced "see-in". Used for input, and uses the extraction operator (>>)

Creating a Simple Calculator

In this example, the user must input two numbers. Then we print the sum by calculating (adding) the two numbers:

Example
  1. int x, y;
  2. int sum;
  3. cout << "Type a number: ";
  4. cin >> x;
  5. cout << "Type another number: ";
  6. cin >> y;
  7. sum = x + y;
  8. cout << "Sum is: " << sum;
C++ Exercises
Test Yourself With Exercises
Exercise:
Use the correct keyword to get user input, stored in the variable x:
  1. int x;
  2. cout << "Type a number: ";
  3.  ___>> _____
  4. ;
Submit Answer »

C++ Data Types

As explained in the Variables chapter, a variable in C++ must be a specified data type:

Example
  1. int myNum = 5;               // Integer (whole number)
  2. float myFloatNum = 5.99;     // Floating point number
  3. double myDoubleNum = 9.98;   // Floating point number
  4. char myLetter = 'D';         // Character
  5. bool myBoolean = true;       // Boolean
  6. string myText = "Hello";     // String

Basic Data Types

The data type specifies the size and type of information the variable will store:

Data Type

Size

Description

Boolean

1 byte

Stores true or false values

char

1 byte

Stores a single character/letter/number, or ASCII values

int

2 or 4 bytes

Stores whole numbers, without decimals

float

4 bytes

Stores fractional numbers, containing one or more decimals. Sufficient for storing 6-7 decimal digits

double

8 bytes

Stores fractional numbers, containing one or more decimals. Sufficient for storing 15 decimal digits


You will learn more about the individual data types in the next chapters.

C++ Exercises
Test Yourself With Exercises
Exercise:
Add the correct data type for the following variables:
  1.  ______ myNum = 9;
  2.  ______ myDoubleNum = 8.99;
  3.  ______ myLetter = 'A';
  4. _______ myBool = false;
  5. _______ myText = "Hello World";

Submit Answer »

Numeric Types

Use int when you need to store a whole number without decimals, like 35 or 1000, and float or double when you need a floating point number (with decimals), like 9.99 or 3.14515.
int:- 
  1. int myNum = 1000;
  2. cout << myNum;
float:-
  1. float myNum = 5.75;
  2. cout << myNum;
double:-
  1. double myNum = 19.99;
  2. cout << myNum;

float vs. double

The precision of a floating point value indicates how many digits the value can have after the decimal point. The precision of float is only six or seven decimal digits, while double variables have a precision of about 15 digits. Therefore it is safer to use double for most calculations.

Scientific Numbers
A floating point number can also be a scientific number with an "e" to indicate the power of 10:

Example
  1. float f1 = 35e3;
  2. double d1 = 12E4;
  3. cout << f1;
  4. cout << d1;

Boolean Types

A boolean data type is declared with the bool keyword and can only take the values true or false.

When the value is returned, true = 1 and false = 0.

Example
  1. bool isCodingFun = true;
  2. bool isFishTasty = false;
  3. cout << isCodingFun;  // Outputs 1 (true)
  4. cout << isFishTasty;  // Outputs 0 (false)

Boolean values are mostly used for conditional testing, which you will learn more about in a later chapter.

Character Types

The char data type is used to store a single character. The character must be surrounded by single quotes, like 'A' or 'c':

Example
  1. char myGrade = 'B';
  2. cout << myGrade;
Alternatively, you can use ASCII values to display certain characters:

Example
  1. char a = 65, b = 66, c = 67;
  2. cout << a;
  3. cout << b;
  4. cout << c;

String Types

The string type is used to store a sequence of characters (text). This is not a built-in type, but it behaves like one in its most basic usage. String values must be surrounded by double quotes:

Example
  1. string greeting = "Hello";
  2. cout << greeting;
To use strings, you must include an additional header file in the source code, the <string> library:

Example
  1. // Include the string library
  2. #include <string>

  3. // Create a string variable
  4. string greeting = "Hello";

  5. // Output string value
  6. cout << greeting;
You will learn more about strings, in our C++ Strings Chapter.

C++ Operators

Operators are used to perform operations on variables and values.

In the example below, we use the + operator to add together two values:

Example
  1. int x = 100 + 50;
Although the + operator is often used to add together two values, like in the example above, it can also be used to add together a variable and a value, or a variable and another variable:

Example
  1. int sum1 = 100 + 50;        // 150 (100 + 50)
  2. int sum2 = sum1 + 250;      // 400 (150 + 250)
  3. int sum3 = sum2 + sum2;     // 800 (400 + 400)
C++ divides the operators into the following groups:
  • Arithmetic operators
  • Assignment operators
  • Comparison operators
  • Logical operators
  • Bitwise operators

Arithmetic Operators

Arithmetic operators are used to perform common mathematical operations.

Operator

Name

Description

Example

+

Addition

Adds together two values

x + y

-

Subtraction

Subtracts one value from another

x - y

*

Multiplication

Multiplies two values

x * y

/

Division

Divides one value by another

x / y

%

Modulus

Returns the division remainder

x % y

++

Increment

Increases the value of a variable by 1

++x

--

Decrement

Decreases the value of a variable by 1

--x


C++ Exercises
Test Yourself With Exercises
Exercise:
Multiply 10 with 5, and print the result.

  1. cout << 10 _____  5;
Submit Answer »

Assignment Operators

Assignment operators are used to assign values to variables.

In the example below, we use the assignment operator (=) to assign the value 10 to a variable called x:

Example
  1. int x = 10;
The addition assignment operator (+=) adds a value to a variable:

Example
  1. int x = 10;
  2. x += 5;
A list of all assignment operators:

Operator

Example

Same As

=

x = 5

x = 5

+=

x += 3

x = x + 3

-=

x -= 3

x = x - 3

*=

x *= 3

x = x * 3

/=

x /= 3

x = x / 3

%=

x %= 3

x = x % 3

&=

x &= 3

x = x & 3

|=

x |= 3

x = x | 3

^=

x ^= 3

x = x ^ 3

>>=

x >>= 3

x = x >> 3

<<=

x <<= 3

x = x << 3


Comparison Operators

Comparison operators are used to compare two values (or variables). This is important in programming, because it helps us to find answers and make decisions.

The return value of a comparison is either 1 or 0, which means true (1) or false (0). These values are known as Boolean values, and you will learn more about them in the Booleans and If..Else chapter.

In the following example, we use the greater than operator (>) to find out if 5 is greater than 3:

Example
  1. int x = 5;
  2. int y = 3;
  3. cout << (x > y); // returns 1 (true) because 5 is greater than 3
A list of all comparison operators:

Operator

Name

Example

==

Equal to

x == y

!=

Not equal

x! = y

> 

Greater than

x > y

< 

Less than

x < y

>=

Greater than or equal to

x >= y

<=

Less than or equal to

x <= y


You will learn much more about comparison operators and how to use them in a later chapter.

Logical Operators

As with comparison operators, you can also test for true (1) or false (0) values with logical operators.

Logical operators are used to determine the logic between variables or values:

Operator

Name

Description

Example

&&

Logical and

Returns true if both statements are true

x < 5 && x < 10

||

Logical or

Returns true if one of the statements is true

x < 5 || x < 4

!

Logical not

Reverse the result, returns false if the result is true

!(x < 5 && x < 10)


You will learn much more about true and false values in a later chapter.

C++ Strings

Strings are used for storing text.

A string variable contains a collection of characters surrounded by double quotes:

Example
Create a variable of type string and assign it a value:
  1. string greeting = "Hello";
To use strings, you must include an additional header file in the source code, the <string> library:

Example
  1. // Include the string library
  2. #include <string>

  3. // Create a string variable
  4. string greeting = "Hello";
C++ Exercises
Test Yourself With Exercises
Exercise:
Fill in the missing part to create a greeting variable of type string and assign it the value Hello.
  1. ______  _______ = _______ ;
Submit Answer »

String Concatenation

The + operator can be used between strings to add them together to make a new string. This is called concatenation:

Example
  1. string firstName = "John ";
  2. string lastName = "Doe";
  3. string fullName = firstName + lastName;
  4. cout << fullName;
In the example above, we added a space after firstName to create a space between John and Doe on output. However, you could also add a space with quotes (" " or ' '):

Example
  1. string firstName = "John";
  2. string lastName = "Doe";
  3. string fullName = firstName + " " + lastName;
  4. cout << fullName;
Append
A string in C++ is actually an object, which contain functions that can perform certain operations on strings. For example, you can also concatenate strings with the append() function:

Example
  1. string firstName = "John ";
  2. string lastName = "Doe";
  3. string fullName = firstName.append(lastName);
  4. cout << fullName;

Adding Numbers and Strings

WARNING!

C++ uses the + operator for both addition and concatenation.

Numbers are added. Strings are concatenated.

If you add two numbers, the result will be a number:

Example
  1. int x = 10;
  2. int y = 20;
  3. int z = x + y;      // z will be 30 (an integer)

If you add two strings, the result will be a string concatenation:

Example
  1. string x = "10";
  2. string y = "20";
  3. string z = x + y;   // z will be 1020 (a string)

If you try to add a number to a string, an error occurs:

Example
  1. string x = "10";
  2. int y = 20;
  3. string z = x + y;

String Length

To get the length of a string, use the length() function:

Example
  1. string txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  2. cout << "The length of the txt string is: " << txt.length();

Tip: You might see some C++ programs that use the size() function to get the length of a string. This is just an alias of length(). It is completely up to you if you want to use length() or size():

Example
  1. string txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  2. cout << "The length of the txt string is: " << txt.size();

Access Strings

You can access the characters in a string by referring to its index number inside square brackets [].

This example prints the first character in myString:

Example
  1. string myString = "Hello";
  2. cout << myString[0];
  3. // Outputs H

Note: String indexes start with 0: [0] is the first character. [1] is the second character, etc.

This example prints the second character in myString:

Example
  1. string myString = "Hello";
  2. cout << myString[1];
  3. // Outputs e

Change String Characters
To change the value of a specific character in a string, refer to the index number, and use single quotes:

Example
  1. string myString = "Hello";
  2. myString[0] = 'J';
  3. cout << myString;
  4. // Outputs Jello instead of Hello


Strings - Special Characters

Because strings must be written within quotes, C++ will misunderstand this string, and generate an error:

  • string txt = "We are the so-called "Vikings" from the north.";
The solution to avoid this problem, is to use the backslash escape character.

The backslash (\) escape character turns special characters into string characters:

Escape character

Result

Description

\'

'

Single quote

\"

"

Double quote

\\

\

Backslash


The sequence \"  inserts a double quote in a string:

Example
  1. string txt = "We are the so-called \"Vikings\" from the north.";
The sequence \'  inserts a single quote in a string:

Example
  1. string txt = "It\'s alright.";
The sequence \\  inserts a single backslash in a string:

Example
  1. string txt = "The character \\ is called backslash.";
Other popular escape characters in C++ are:

Escape Character

Result

\n

New Line

\t

Tab


User Input Strings

It is possible to use the extraction operator >> on cin to display a string entered by a user:

Example
  1. string firstName;
  2. cout << "Type your first name: ";
  3. cin >> firstName; // get user input from the keyboard
  4. cout << "Your name is: " << firstName;

  5. // Type your first name: John
  6. // Your name is: John
However, cin considers a space (whitespace, tabs, etc) as a terminating character, which means that it can only display a single word (even if you type many words):

Example
  1. string fullName;
  2. cout << "Type your full name: ";
  3. cin >> fullName;
  4. cout << "Your name is: " << fullName;

  5. // Type your full name: John Doe
  6. // Your name is: John
From the example above, you would expect the program to print "John Doe", but it only prints "John".

That's why, when working with strings, we often use the getline() function to read a line of text. It takes cin as the first parameter, and the string variable as second:

Example
  1. string fullName;
  2. cout << "Type your full name: ";
  3. getline (cin, fullName);
  4. cout << "Your name is: " << fullName;

  5. // Type your full name: John Doe
  6. // Your name is: John Doe

Omitting Namespace

You might see some C++ programs that runs without the standard namespace library. The using namespace std line can be omitted and replaced with the std keyword, followed by the :: operator for string (and cout) objects:

Example
  1. #include <iostream>
  2. #include <string>

  3. int main() {
  4.   std::string greeting = "Hello";
  5.   std::cout << greeting;
  6.   return 0;
  7. }
It is up to you if you want to include the standard namespace library or not.

C++ Math

C++ has many functions that allows you to perform mathematical tasks on numbers.

Max and min
The max(x,y) function can be used to find the highest value of x and y:

Example
  1. cout << max(5, 10);
And the min(x,y) function can be used to find the lowest value of x and y:

Example
  1. cout << min(5, 10);
C++ <cmath> Header
Other functions, such as sqrt (square root), round (rounds a number) and log (natural logarithm), can be found in the <cmath> header file:

Example
  1. // Include the cmath library
  2. #include <cmath>

  3. cout << sqrt(64);
  4. cout << round(2.6);
  5. cout << log(2);

Other Math Functions

A list of other popular Math functions (from the <cmath> library) can be found in the table below:

Function

Description

abs(x)

Returns the absolute value of x

acos(x)

Returns the arccosine of x

asin(x)

Returns the arcsine of x

atan(x)

Returns the arctangent of x

cbrt(x)

Returns the cube root of x

ceil(x)

Returns the value of x rounded up to its nearest integer

cos(x)

Returns the cosine of x

cosh(x)

Returns the hyperbolic cosine of x

exp(x)

Returns the value of Ex

expm1(x)

Returns ex -1

fabs(x)

Returns the absolute value of a floating x

fdim(x, y)

Returns the positive difference between x and y

floor(x)

Returns the value of x rounded down to its nearest integer

hypot(x, y)

Returns sqrt(x2 +y2) without intermediate overflow or underflow

fma(x, y, z)

Returns x*y+z without losing precision

fmax(x, y)

Returns the highest value of a floating x and y

fmin(x, y)

Returns the lowest value of a floating x and y

fmod(x, y)

Returns the floating point remainder of x/y

pow(x, y)

Returns the value of x to the power of y

sin(x)

Returns the sine of x (x is in radians)

sinh(x)

Returns the hyperbolic sine of a double value

tan(x)

Returns the tangent of an angle

tanh(x)

Returns the hyperbolic tangent of a double value


C++ Exercises
Test Yourself With Exercises
Exercise:
Use the correct function to print the highest value of x and y.
  1. int x = 5;
  2. int y = 10;
  3. cout << ______ (x, y);
Submit Answer »

C++ Booleans

Very often, in programming, you will need a data type that can only have one of two values, like:
  • YES / NO
  • ON / OFF
  • TRUE / FALSE
For this, C++ has a bool data type, which can take the values true (1) or false (0).

Boolean Values

A boolean variable is declared with the bool keyword and can only take the values true or false:

Example
  1. bool isCodingFun = true;
  2. bool isFishTasty = false;
  3. cout << isCodingFun;  // Outputs 1 (true)
  4. cout << isFishTasty;  // Outputs 0 (false)
From the example above, you can read that a true value returns 1, and false returns 0.

However, it is more common to return a boolean value by comparing values and variables (see next page).

Boolean Expression

A Boolean expression returns a boolean value that is either 1 (true) or 0 (false).

This is useful to build logic, and find answers.

You can use a comparison operator, such as the greater than (>) operator, to find out if an expression (or variable) is true or false:

Example
  1. int x = 10;
  2. int y = 9;
  3. cout << (x > y); // returns 1 (true), because 10 is higher than 9

Or even easier:

Example
  1. cout << (10 > 9); // returns 1 (true), because 10 is higher than 9

In the examples below, we use the equal to (==) operator to evaluate an expression:

Example
  1. int x = 10;
  2. cout << (x == 10);  // returns 1 (true), because the value of x is equal to 10

Example
  1. cout << (10 == 15);  // returns 0 (false), because 10 is not equal to 15

Real Life Example
Let's think of a "real life example" where we need to find out if a person is old enough to vote.

In the example below, we use the >= comparison operator to find out if the age (25) is greater than OR equal to the voting age limit, which is set to 18:

Example
  1. int myAge = 25;
  2. int votingAge = 18;

  3. cout << (myAge >= votingAge); // returns 1 (true), meaning 25 year olds are allowed to vote!
Cool, right? An even better approach (since we are on a roll now), would be to wrap the code above in an if...else statement, so we can perform different actions depending on the result:

Example
Output "Old enough to vote!" if myAge is greater than or equal to 18. Otherwise output "Not old enough to vote.":
  1. int myAge = 25;
  2. int votingAge = 18;

  3. if (myAge >= votingAge) {
  4.   cout << "Old enough to vote!";
  5. } else {
  6.   cout << "Not old enough to vote.";
  7. }

  8. // Outputs: Old enough to vote!
Booleans are the basis for all C++ comparisons and conditions.

C++ Exercises
Test Yourself With Exercises
Exercise:
Fill in the missing parts to print the values 1 (for true) and 0 (for false):
  1.  ____ isCodingFun = true;
  2.  _____ isFishTasty = false;
  3. cout << ______ ;
  4. cout << _____ ;
Submit Answer »

C++ Conditions and If Statements

You already know that C++ supports the usual logical conditions from mathematics:

  • Less than: a < b
  • Less than or equal to: a <= b
  • Greater than: a > b
  • Greater than or equal to: a >= b
  • Equal to a == b
  • Not Equal to: a != b
You can use these conditions to perform different actions for different decisions.

C++ has the following conditional statements:
  • Use if to specify a block of code to be executed, if a specified condition is true
  • Use else to specify a block of code to be executed, if the same condition is false
  • Use else if to specify a new condition to test, if the first condition is false
  • Use switch to specify many alternative blocks of code to be executed

The if Statement

Use the if statement to specify a block of C++ code to be executed if a condition is true.

Syntax
  1. if (condition) {
  2.   // block of code to be executed if the condition is true
  3. }
Note that if is in lowercase letters. Uppercase letters (If or IF) will generate an error.

In the example below, we test two values to find out if 20 is greater than 18. If the condition is true, print some text:

Example
  1. if (20 > 18) {
  2.   cout << "20 is greater than 18";
  3. }
We can also test variables:

Example
  1. int x = 20;
  2. int y = 18;
  3. if (x > y) {
  4.   cout << "x is greater than y";
  5. }
Example explained
In the example above we use two variables, x and y, to test whether x is greater than y (using the > operator). As x is 20, and y is 18, and we know that 20 is greater than 18, we print to the screen that "x is greater than y".

C++ Exercises
Test Yourself With Exercises
Exercise:
Print "Hello World" if x is greater than y.

  1. int x = 50;
  2. int y = 10;
  3. ______ (x ______  y) {
  4.   cout << "Hello World";
  5. }
Submit Answer »

The else Statement

Use the else statement to specify a block of code to be executed if the condition is false.

Syntax
  1. if (condition) {
  2.   // block of code to be executed if the condition is true
  3. } else {
  4.   // block of code to be executed if the condition is false
  5. }
Example
  1. int time = 20;
  2. if (time < 18) {
  3.   cout << "Good day.";
  4. } else {
  5.   cout << "Good evening.";
  6. }
  7. // Outputs "Good evening."
Example explained
In the example above, time (20) is greater than 18, so the condition is false. Because of this, we move on to the else condition and print to the screen "Good evening". If the time was less than 18, the program would print "Good day".

The else-if Statement

Use the else if statement to specify a new condition if the first condition is false.

Syntax
  1. if (condition1) {
  2.   // block of code to be executed if condition1 is true
  3. } else if (condition2) {
  4.   // block of code to be executed if the condition1 is false and condition2 is true
  5. } else {
  6.   // block of code to be executed if the condition1 is false and condition2 is false
  7. }
Example
  1. int time = 22;
  2. if (time < 10) {
  3.   cout << "Good morning.";
  4. } else if (time < 20) {
  5.   cout << "Good day.";
  6. } else {
  7.   cout << "Good evening.";
  8. }
  9. // Outputs "Good evening."
Example explained
In the example above, time (22) is greater than 10, so the first condition is false. The next condition, in the else if statement, is also false, so we move on to the else condition since condition1 and condition2 is both false - and print to the screen "Good evening".

However, if the time was 14, our program would print "Good day."

Short Hand If...Else (Ternary Operator)

There is also a short-hand if else, which is known as the ternary operator because it consists of three operands. It can be used to replace multiple lines of code with a single line. It is often used to replace simple if else statements:

Syntax
  1. variable = (condition) ? expressionTrue : expressionFalse;
Instead of writing:

Example
  1. int time = 20;
  2. if (time < 18) {
  3.   cout << "Good day.";
  4. } else {
  5.   cout << "Good evening.";
  6. }
You can simply write:

Example
  1. int time = 20;
  2. string result = (time < 18) ? "Good day." : "Good evening.";
  3. cout << result;

C++ Switch Statements

Use the switch statement to select one of many code blocks to be executed.

Syntax
  1. switch(expression) {
  2.   case x:
  3.     // code block
  4.     break;
  5.   case y:
  6.     // code block
  7.     break;
  8.   default:
  9.     // code block
  10. }
This is how it works:
  • The switch expression is evaluated once
  • The value of the expression is compared with the values of each case
  • If there is a match, the associated block of code is executed
  • The break and default keywords are optional, and will be described later in this chapter
The example below uses the weekday number to calculate the weekday name:

Example
  1. int day = 4;
  2. switch (day) {
  3.   case 1:
  4.     cout << "Monday";
  5.     break;
  6.   case 2:
  7.     cout << "Tuesday";
  8.     break;
  9.   case 3:
  10.     cout << "Wednesday";
  11.     break;
  12.   case 4:
  13.     cout << "Thursday";
  14.     break;
  15.   case 5:
  16.     cout << "Friday";
  17.     break;
  18.   case 6:
  19.     cout << "Saturday";
  20.     break;
  21.   case 7:
  22.     cout << "Sunday";
  23.     break;
  24. }
  25. // Outputs "Thursday" (day 4)

The break Keyword
When C++ reaches a break keyword, it breaks out of the switch block.

This will stop the execution of more code and case testing inside the block.

When a match is found, and the job is done, it's time for a break. There is no need for more testing.

A break can save a lot of execution time because it "ignores" the execution of all the rest of the code in the switch block.

The default Keyword

The default keyword specifies some code to run if there is no case match:

Example
  1. int day = 4;
  2. switch (day) {
  3.   case 6:
  4.     cout << "Today is Saturday";
  5.     break;
  6.   case 7:
  7.     cout << "Today is Sunday";
  8.     break;
  9.   default:
  10.     cout << "Looking forward to the Weekend";
  11. }
  12. // Outputs "Looking forward to the Weekend"

C++ Exercises
Test Yourself With Exercises
Exercise:
Insert the missing parts to complete the following switch statement.

  1. int day = 2;
  2. switch ( ______ ) {
  3.  _____ 1:
  4.     cout << "Saturday";
  5.     break;
  6.  _______ 2:
  7.     cout << "Sunday";
  8.  _________   ;
  9. }
Submit Answer »

C++ Loops

Loops can execute a block of code as long as a specified condition is reached.

Loops are handy because they save time, reduce errors, and they make code more readable.

C++ While Loop

The while loop loops through a block of code as long as a specified condition is true:

Syntax
  1. while (condition) {
  2.   // code block to be executed
  3. }
In the example below, the code in the loop will run, over and over again, as long as a variable (i) is less than 5:

Example
  1. int i = 0;
  2. while (i < 5) {
  3.   cout << i << "\n";
  4.   i++;
  5. }

Note: Do not forget to increase the variable used in the condition, otherwise the loop will never end!

C++ Exercises
Test Yourself With Exercises
Exercise:
Print i as long as i is less than 6.

  1. int i = 1;
  2.  ______ (i < 6) {
  3.   cout << i << "\n";
  4.   _______ ;
  5. }
Submit Answer »

The Do/While Loop

The do/while loop is a variant of the while loop. This loop will execute the code block once, before checking if the condition is true, then it will repeat the loop as long as the condition is true.

Syntax
  1. do {
  2.   // code block to be executed
  3. }
  4. while (condition);
The example below uses a do/while loop. The loop will always be executed at least once, even if the condition is false, because the code block is executed before the condition is tested:

Example
  1. int i = 0;
  2. do {
  3.   cout << i << "\n";
  4.   i++;
  5. }
  6. while (i < 5);
Do not forget to increase the variable used in the condition, otherwise the loop will never end!

C++ For Loop

When you know exactly how many times you want to loop through a block of code, use the for loop instead of a while loop:

Syntax
  1. for (statement 1; statement 2; statement 3) {
  2.   // code block to be executed
  3. }
  • Statement 1 is executed (one time) before the execution of the code block.
  • Statement 2 defines the condition for executing the code block.
  • Statement 3 is executed (every time) after the code block has been executed.

The example below will print the numbers 0 to 4:

Example
  1. for (int i = 0; i < 5; i++) {
  2.   cout << i << "\n";
  3. }
Example explained
  • Statement 1 sets a variable before the loop starts (int i = 0).
  • Statement 2 defines the condition for the loop to run (i must be less than 5). If the condition is true, the loop will start over again, if it is false, the loop will end.
  • Statement 3 increases a value (i++) each time the code block in the loop has been executed.

Another Example

This example will only print even values between 0 and 10:

Example
  1. for (int i = 0; i <= 10; i = i + 2) {
  2.   cout << i << "\n";
  3. }

Nested Loops

It is also possible to place a loop inside another loop. This is called a nested loop.

The "inner loop" will be executed one time for each iteration of the "outer loop":

Example
  1. // Outer loop
  2. for (int i = 1; i <= 2; ++i) {
  3.   cout << "Outer: " << i << "\n"; // Executes 2 times

  4.   // Inner loop
  5.   for (int j = 1; j <= 3; ++j) {
  6.     cout << " Inner: " << j << "\n"; // Executes 6 times (2 * 3)
  7.   }
  8. }

The foreach Loop

There is also a "for-each loop" (introduced in C++ version 11 (2011), which is used exclusively to loop through elements in an array (or other data sets):

Syntax
  1. for (type variableName : arrayName) {
  2.   // code block to be executed
  3. }
The following example outputs all elements in an array, using a "for-each loop":

Example
  1. int myNumbers[5] = {10, 20, 30, 40, 50};
  2. for (int i : myNumbers) {
  3.   cout << i << "\n";
  4. }

Note: Don't worry if you don't understand the example above. You will learn more about arrays in the C++ Arrays chapter.

C++ Exercises
Test Yourself With Exercises
Exercise:
Use a for loop to print "Yes" 5 times:
  1.  _______ (int i = 0; i < 5; ______ ) {
  2.   cout << _______  << "\n";
  3. }
Submit Answer »

C++ Break

You have already seen the break statement used in an earlier chapter of this tutorial. It was used to "jump out" of a switch statement.

The break statement can also be used to jump out of a loop.

This example jumps out of the loop when i is equal to 4:

Example
  1. for (int i = 0; i < 10; i++) {
  2.   if (i == 4) {
  3.     break;
  4.   }
  5.   cout << i << "\n";
  6. }

C++ Continue

The continue statement breaks one iteration (in the loop), if a specified condition occurs, and continues with the next iteration in the loop.

This example skips the value of 4:

Example
  1. for (int i = 0; i < 10; i++) {
  2.   if (i == 4) {
  3.     continue;
  4.   }
  5.   cout << i << "\n";
  6. }

Break and Continue in While Loop

You can also use break and continue in while loops:

Break Example
  1. int i = 0;
  2. while (i < 10) {
  3.   cout << i << "\n";
  4.   i++;
  5.   if (i == 4) {
  6.     break;
  7.   }
  8. }

Continue Example
  1. int i = 0;
  2. while (i < 10) {
  3.   if (i == 4) {
  4.     i++;
  5.     continue;
  6.   }
  7.   cout << i << "\n";
  8.   i++;
  9. }

C++ Exercises
Test Yourself With Exercises
Exercise:
Stop the loop if i is 5:

  1. for (int i = 0; i < 10; i++) {
  2.   if (i == 5) {   
  3.     _______
  4. ;
  5.   }
  6.   cout << i << "\n";
  7. }

Submit Answer »

C++ Arrays

Arrays are used to store multiple values in a single variable, instead of declaring separate variables for each value.

To declare an array, define the variable type, specify the name of the array followed by square brackets and specify the number of elements it should store:

  1. string cars[4];
We have now declared a variable that holds an array of four strings. To insert values to it, we can use an array literal - place the values in a comma-separated list, inside curly braces:

  1. string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};
To create an array of three integers, you could write:
  1. int myNum[3] = {10, 20, 30};

Access the Elements of an Array

You access an array element by referring to the index number inside square brackets [].

This statement accesses the value of the first element in cars:

Example
  1. string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};
  2. cout << cars[0];
  3. // Outputs Volvo

Note: Array indexes start with 0: [0] is the first element. [1] is the second element, etc.

Change an Array Element

To change the value of a specific element, refer to the index number:

  1. cars[0] = "Opel";
Example
  1. string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};
  2. cars[0] = "Opel";
  3. cout << cars[0];
  4. // Now outputs Opel instead of Volvo

C++ Exercises
Test Yourself With Exercises
Exercise:
Create an array of type string called cars.
  1. ____ _____[4] = {"Volvo", "BMW", "Ford", "Mazda"};

Submit Answer »

Loop Through an Array

You can loop through the array elements with the for loop.

The following example outputs all elements in the cars array:

Example
  1. string cars[5] = {"Volvo", "BMW", "Ford", "Mazda", "Tesla"};
  2. for (int i = 0; i < 5; i++) {
  3.   cout << cars[i] << "\n";
  4. }

This example outputs the index of each element together with its value:

Example
  1. string cars[5] = {"Volvo", "BMW", "Ford", "Mazda", "Tesla"};
  2. for (int i = 0; i < 5; i++) {
  3.   cout << i << " = " << cars[i] << "\n";
  4. }
And this example shows how to loop through an array of integers:

Example
  1. int myNumbers[5] = {10, 20, 30, 40, 50};
  2. for (int i = 0; i < 5; i++) {
  3.   cout << myNumbers[i] << "\n";
  4. }

The foreach Loop

There is also a "for-each loop" (introduced in C++ version 11 (2011), which is used exclusively to loop through elements in an array:

Syntax
  1. for (type variableName : arrayName) {
  2.   // code block to be executed
  3. }
The following example outputs all elements in an array, using a "for-each loop":

Example
  1. int myNumbers[5] = {10, 20, 30, 40, 50};
  2. for (int i : myNumbers) {
  3.   cout << i << "\n";
  4. }

Omit Array Size

In C++, you don't have to specify the size of the array. The compiler is smart enough to determine the size of the array based on the number of inserted values:

  1. string cars[] = {"Volvo", "BMW", "Ford"}; // Three arrays
The example above is equal to:

  1. string cars[3] = {"Volvo", "BMW", "Ford"}; // Also three arrays
However, the last approach is considered as "good practice", because it will reduce the chance of errors in your program.

Omit Elements on Declaration

It is also possible to declare an array without specifying the elements on declaration, and add them later:

Example
  1. string cars[5];
  2. cars[0] = "Volvo";
  3. cars[1] = "BMW";
  4. ...

Get the Size of an Array

To get the size of an array, you can use the sizeof() operator:

Example
  1. int myNumbers[5] = {10, 20, 30, 40, 50};
  2. cout << sizeof(myNumbers);
Result20

Why did the result show 20 instead of 5, when the array contains 5 elements?

It is because the sizeof() operator returns the size of a type in bytes.

You learned from the Data Types chapter that an int type is usually 4 bytes, so from the example above, 4 x 5 (4 bytes x 5 elements) = 20 bytes.

To find out how many elements an array has, you have to divide the size of the array by the size of the data type it contains:

Example
  1. int myNumbers[5] = {10, 20, 30, 40, 50};
  2. int getArrayLength = sizeof(myNumbers) / sizeof(int);
  3. cout << getArrayLength;
Result5

Loop Through an Array with sizeof()

In the Arrays and Loops Chapter, we wrote the size of the array in the loop condition (i < 5). This is not ideal, since it will only work for arrays of a specified size.

However, by using the sizeof() approach from the example above, we can now make loops that work for arrays of any size, which is more sustainable.

Instead of writing:

  1. int myNumbers[5] = {10, 20, 30, 40, 50};
  2. for (int i = 0; i < 5; i++) {
  3.   cout << myNumbers[i] << "\n";
  4. }
It is better to write:

Example
  1. int myNumbers[5] = {10, 20, 30, 40, 50};
  2. for (int i = 0; i < sizeof(myNumbers) / sizeof(int); i++) {
  3.   cout << myNumbers[i] << "\n";
  4. }

Note that, in C++ version 11 (2011), you can also use the "for-each" loop:

Example
  1. int myNumbers[5] = {10, 20, 30, 40, 50};
  2. for (int i : myNumbers) {
  3.   cout << i << "\n";
  4. }
It is good to know the different ways to loop through an array, since you may encounter them all in different programs.

Multi-Dimensional Arrays

A multi-dimensional array is an array of arrays.

To declare a multi-dimensional array, define the variable type, specify the name of the array followed by square brackets which specify how many elements the main array has, followed by another set of square brackets which indicates how many elements the sub-arrays have:
  1. string letters[2][4];
As with ordinary arrays, you can insert values with an array literal - a comma-separated list inside curly braces. In a multi-dimensional array, each element in an array literal is another array literal.

  1. string letters[2][4] = {
  2.   { "A", "B", "C", "D" },
  3.   { "E", "F", "G", "H" }
  4. };
Each set of square brackets in an array declaration adds another dimension to an array. An array like the one above is said to have two dimensions.

Arrays can have any number of dimensions. The more dimensions an array has, the more complex the code becomes. The following array has three dimensions:
  1. string letters[2][2][2] = {
  2.   {
  3.     { "A", "B" },
  4.     { "C", "D" }
  5.   },
  6.   {
  7.     { "E", "F" },
  8.     { "G", "H" }
  9.   }
  10. };

Access the Elements of a Multi-Dimensional Array

To access an element of a multi-dimensional array, specify an index number in each of the array's dimensions.

This statement accesses the value of the element in the first row (0) and third column (2) of the letters array.

Example
  1. string letters[2][4] = {
  2.   { "A", "B", "C", "D" },
  3.   { "E", "F", "G", "H" }
  4. };

  5. cout << letters[0][2];  // Outputs "C"

Remember that: Array indexes start with 0: [0] is the first element. [1] is the second element, etc.

Change Elements in a Multi-Dimensional Array

To change the value of an element, refer to the index number of the element in each of the dimensions:

Example
  1. string letters[2][4] = {
  2.   { "A", "B", "C", "D" },
  3.   { "E", "F", "G", "H" }
  4. };
  5. letters[0][0] = "Z";

  6. cout << letters[0][0];  // Now outputs "Z" instead of "A"

Loop Through a Multi-Dimensional Array

To loop through a multi-dimensional array, you need one loop for each of the array's dimensions.

The following example outputs all elements in the letters array:

Example
  1. string letters[2][4] = {
  2.   { "A", "B", "C", "D" },
  3.   { "E", "F", "G", "H" }
  4. };

  5. for (int i = 0; i < 2; i++) {
  6.   for (int j = 0; j < 4; j++) {
  7.     cout << letters[i][j] << "\n";
  8.   }
  9. }

This example shows how to loop through a three-dimensional array:

Example
  1. string letters[2][2][2] = {
  2.   {
  3.     { "A", "B" },
  4.     { "C", "D" }
  5.   },
  6.   {
  7.     { "E", "F" },
  8.     { "G", "H" }
  9.   }
  10. };

  11. for (int i = 0; i < 2; i++) {
  12.   for (int j = 0; j < 2; j++) {
  13.     for (int k = 0; k < 2; k++) {
  14.       cout << letters[i][j][k] << "\n";
  15.     }
  16.   }
  17. }

Why Multi-Dimensional Arrays?

Multi-dimensional arrays are great at representing grids. This example shows a practical use for them. In the following example we use a multi-dimensional array to represent a small game of Battleship:

Example
  1. // We put "1" to indicate there is a ship.
  2. bool ships[4][4] = {
  3.   { 0, 1, 1, 0 },
  4.   { 0, 0, 0, 0 },
  5.   { 0, 0, 1, 0 },
  6.   { 0, 0, 1, 0 }
  7. };

  8. // Keep track of how many hits the player has and how many turns they have played in these variables
  9. int hits = 0;
  10. int numberOfTurns = 0;

  11. // Allow the player to keep going until they have hit all four ships
  12. while (hits < 4) {
  13.   int row, column;

  14.   cout << "Selecting coordinates\n";

  15.   // Ask the player for a row
  16.   cout << "Choose a row number between 0 and 3: ";
  17.   cin >> row;

  18.   // Ask the player for a column
  19.   cout << "Choose a column number between 0 and 3: ";
  20.   cin >> column;

  21.   // Check if a ship exists in those coordinates
  22.   if (ships[row][column]) {
  23.     // If the player hit a ship, remove it by setting the value to zero.
  24.     ships[row][column] = 0;

  25.     // Increase the hit counter
  26.     hits++;

  27.     // Tell the player that they have hit a ship and how many ships are left
  28.     cout << "Hit! " << (4-hits) << " left.\n\n";
  29.   } else {
  30.     // Tell the player that they missed
  31.     cout << "Miss\n\n";
  32.   }

  33.   // Count how many turns the player has taken
  34.   numberOfTurns++;
  35. }

  36. cout << "Victory!\n";
  37. cout << "You won in " << numberOfTurns << " turns";

C++ Structures

Structures (also called structs) are a way to group several related variables into one place. Each variable in the structure is known as a member of the structure.

Unlike an array, a structure can contain many different data types (int, string, bool, etc.).

Create a Structure

To create a structure, use the struct keyword and declare each of its members inside curly braces.

After the declaration, specify the name of the structure variable (myStructure in the example below):

  1. struct {             // Structure declaration
  2.   int myNum;         // Member (int variable)
  3.   string myString;   // Member (string variable)
  4. } myStructure;       // Structure variable

Access Structure Members

To access members of a structure, use the dot syntax (.):

Example
Assign data to members of a structure and print it:

  1. // Create a structure variable called myStructure
  2. struct {
  3.   int myNum;
  4.   string myString;
  5. } myStructure;

  6. // Assign values to members of myStructure
  7. myStructure.myNum = 1;
  8. myStructure.myString = "Hello World!";

  9. // Print members of myStructure
  10. cout << myStructure.myNum << "\n";
  11. cout << myStructure.myString << "\n";
One Structure in Multiple Variables
You can use a comma (,) to use one structure in many variables:

  1. struct {
  2.   int myNum;
  3.   string myString;
  4. } myStruct1, myStruct2, myStruct3; // Multiple structure variables separated with commas
This example shows how to use a structure in two different variables:

Example
Use one structure to represent two cars:

  1. struct {
  2.   string brand;
  3.   string model;
  4.   int year;
  5. } myCar1, myCar2; // We can add variables by separating them with a comma here

  6. // Put data into the first structure
  7. myCar1.brand = "BMW";
  8. myCar1.model = "X5";
  9. myCar1.year = 1999;

  10. // Put data into the second structure
  11. myCar2.brand = "Ford";
  12. myCar2.model = "Mustang";
  13. myCar2.year = 1969;

  14. // Print the structure members
  15. cout << myCar1.brand << " " << myCar1.model << " " << myCar1.year << "\n";
  16. cout << myCar2.brand << " " << myCar2.model << " " << myCar2.year << "\n";

Named Structures

By giving a name to the structure, you can treat it as a data type. This means that you can create variables with this structure anywhere in the program at any time.

To create a named structure, put the name of the structure right after the struct keyword:

  1. struct myDataType { // This structure is named "myDataType"
  2.   int myNum;
  3.   string myString;
  4. };
To declare a variable that uses the structure, use the name of the structure as the data type of the variable:
  1. myDataType myVar;
Example
Use one structure to represent two cars:

  1. // Declare a structure named "car"
  2. struct car {
  3.   string brand;
  4.   string model;
  5.   int year;
  6. };

  7. int main() {
  8.   // Create a car structure and store it in myCar1;
  9.   car myCar1;
  10.   myCar1.brand = "BMW";
  11.   myCar1.model = "X5";
  12.   myCar1.year = 1999;

  13.   // Create another car structure and store it in myCar2;
  14.   car myCar2;
  15.   myCar2.brand = "Ford";
  16.   myCar2.model = "Mustang";
  17.   myCar2.year = 1969;
  18.  
  19.   // Print the structure members
  20.   cout << myCar1.brand << " " << myCar1.model << " " << myCar1.year << "\n";
  21.   cout << myCar2.brand << " " << myCar2.model << " " << myCar2.year << "\n";
  22.  
  23.   return 0;
  24. }

Creating References

A reference variable is a "reference" to an existing variable, and it is created with the & operator:

  1. string food = "Pizza";  // food variable
  2. string &meal = food;    // reference to food
Now, we can use either the variable name food or the reference name meal to refer to the food variable:

Example
  1. string food = "Pizza";
  2. string &meal = food;

  3. cout << food << "\n";  // Outputs Pizza
  4. cout << meal << "\n";  // Outputs Pizza

Memory Address

In the example from the previous page, the & operator was used to create a reference variable. But it can also be used to get the memory address of a variable; which is the location of where the variable is stored on the computer.

When a variable is created in C++, a memory address is assigned to the variable. And when we assign a value to the variable, it is stored in this memory address.

To access it, use the & operator, and the result will represent where the variable is stored:

Example
  1. string food = "Pizza";

  2. cout << &food; // Outputs 0x6dfed4
Note: The memory address is in hexadecimal form (0x..). Note that you may not get the same result in your program.

And why is it useful to know the memory address?
References and Pointers (which you will learn about in the next chapter) are important in C++, because they give you the ability to manipulate the data in the computer's memory - which can reduce the code and improve the performance.

These two features are one of the things that make C++ stand out from other programming languages, like Python and Java.

Creating Pointers

You learned from the previous chapter, that we can get the  memory address of a variable by using the & operator:

Example
  1. string food = "Pizza"; // A food variable of type string

  2. cout << food;  // Outputs the value of food (Pizza)
  3. cout << &food; // Outputs the memory address of food (0x6dfed4)

A pointer however, is a variable that stores the memory address as its value.

A pointer variable points to a data type (like int or string) of the same type, and is created with the * operator. The address of the variable you're working with is assigned to the pointer:

Example
  1. string food = "Pizza";  // A food variable of type string
  2. string* ptr = &food;    // A pointer variable, with the name ptr, that stores the address of food

  3. // Output the value of food (Pizza)
  4. cout << food << "\n";

  5. // Output the memory address of food (0x6dfed4)
  6. cout << &food << "\n";

  7. // Output the memory address of food with the pointer (0x6dfed4)
  8. cout << ptr << "\n";
Example explained
Create a pointer variable with the name ptr, that points to a string variable, by using the asterisk sign * (string* ptr). Note that the type of the pointer has to match the type of the variable you're working with.

Use the & operator to store the memory address of the variable called food, and assign it to the pointer.

Now, ptr holds the value of food's memory address.

Tip: There are three ways to declare pointer variables, but the first way is preferred:

  1. string* mystring; // Preferred
  2. string *mystring;
  3. string * mystring;
C++ Exercises
Test Yourself With Exercises
Exercise:
Create a pointer variable with the name ptr, that should point to a string variable named food:
  1. string food = "Pizza";
  2.  ______  _____  = & ______ ;
Submit Answer »

Get Memory Address and Value

In the example from the previous page, we used the pointer variable to get the memory address of a variable (used together with the & reference operator). However, you can also use the pointer to get the value of the variable, by using the * operator (the dereference operator):

Example
  1. string food = "Pizza";  // Variable declaration
  2. string* ptr = &food;    // Pointer declaration

  3. // Reference: Output the memory address of food with the pointer (0x6dfed4)
  4. cout << ptr << "\n";

  5. // Dereference: Output the value of food with the pointer (Pizza)
  6. cout << *ptr << "\n";
Note that the * sign can be confusing here, as it does two different things in our code:
  • When used in declaration (string* ptr), it creates a pointer variable.
  • When not used in declaration, it act as a dereference operator.

Modify the Pointer Value

You can also change the pointer's value. But note that this will also change the value of the original variable:

Example
  1. string food = "Pizza";
  2. string* ptr = &food;

  3. // Output the value of food (Pizza)
  4. cout << food << "\n";

  5. // Output the memory address of food (0x6dfed4)
  6. cout << &food << "\n";

  7. // Access the memory address of food and output its value (Pizza)
  8. cout << *ptr << "\n";

  9. // Change the value of the pointer
  10. *ptr = "Hamburger";

  11. // Output the new value of the pointer (Hamburger)
  12. cout << *ptr << "\n";

  13. // Output the new value of the food variable (Hamburger)
  14. cout << food << "\n";

Comments

Popular posts from this blog

Learning C++ Part 2 Example

BCA Syllabus Topics