How to Declare and Use Variables in C++ Programming

This is an excerpt from chapter two of my book, Practical C++ for Beginners: A Concise and friendly introduction to programming. It makes C++ programming easy and practical. The book is available on Amazon.

C++ programming book

Data Types in C++

A data type is a classification of data which tells a compiler the type of value assigned to a variable and the types of operations that can be carried out on it.
The following data types are assigned to variables in C++:
i. int: A whole number such as 3 and 197.
ii. string: A collection of characters enclosed in quotes.
iii. float: A number with decimal point correct to six decimal places.
iv. double: A number with a decimal point correct to ten decimal places
v. bool: A Boolean value of true or false.
vi. char: A single character enclosed in single quotes.

Variables in C++

A variable is a named memory location which holds a value. In this context, it is a container that holds a value. The container is given a name for referencing the content of the container. The content of the variable can change. The following rules must be observed in giving names to variables:
i. Names of variables must start with letters or underscores.
ii. Names of variables are case sensitive (myName and MyName are different variables).
iii. Whitespaces are not allowed in names of variables.
iv. Special characters such as #, %, !, et cetera are not allowed
v. Reserved keywords in C++ (e. g. int, while, class, etc.) as not allowed
Variables must be declared before they can be used in C++ programs. The syntax for creating or declaring variable is as follows:
Datatype nameOfVariable = value;
If you do not want the value of a variable to change, use the keyword const to declare it. For example, const secondsPerMinute = 60;

Using data types and variables in a C++ program

#include <iostream>
using namespace std;
int main()
{
// Declare variables. Line 7
int num1 = 7;
float num2 = 9.81;
double num3 = 3.1428571;
string myName = "Dan";
char grade = 'A';
bool isTall = true;
/*
This is a multi-line comment
Print or display the value of each variable
*/
cout << num1 << endl;
cout << num2 << "\n";
cout << num3 << "\n";
cout << myName << "\n";
cout << grade << "\n";
cout << isTall;
return 0;
}

The C++ Program Explained

In line 7, there is a single line comment. Comments are used to clarify statements in a code. They are ignored by the compiler. A multi-line comment is included in lines 15 through 18.
In lines 8 through 13, variables of different types are declared and initialized (assigned values).
In line 19 through 24, instructions for printing the values of the variables are given.
In the output, the value of isTall is 1. True has the numerical value of 1 while false is 0.

C. O. Daniel

C. O. Daniel holds degrees in Computer Science and certifications from CompTIA and Microsoft. His areas of interest include computer networking, cybersecurity and programming.

Leave a Reply