C++ Declare Variables

Declaring (Creating) Variables


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

Syntax

   

 

 Where type is one of C++ types (such as int), and variable 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:

 

 

 

Try it yourself!

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

Example


 

  

 

Try it yourself!

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

Example


 

 

Other Types

A demonstration of other data types:

Example


 

 

 

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


 

 

Try it yourself! 

Add Variables Together

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

Example


 

 

 

Test Yourself with Exercises

Exercise:

Create a variable named myNum and assign the value 50 to it


 

Comments

Popular posts from this blog

ភាសាកម្មវិធី C++៖ សង្ខេប

សំណួរ និងលំហាត់៖ ភាពខុស​គ្នា​រវាងភាសា C និងភាសា C++

How to download and install Cambridge Advanced Learner's Dictionary_Fourth Edition-CALD4