Intro to C++ : Variables, Constants, & Data Types

Variables

They are the fundamental building block for programming. A variable is a named memory location which temporarily stores data that can change while the program is running.

Defining a Variable
Here is a few ways to define a variable in which you give it a type and a name.

int a;
char b;

You can also give a variable a value on definition.

int c = 10;
char d ='d';

An array is a variable that can store multiple items of data unlike a regular variable which can only store one piece of data. Yes, arrays can be variables.

int nums[6];

The pieces of data are stored sequentially in array β€œelements” that are numbered starting at zero. So the first value is stored in element zero , the second value is stored in element one and so on.

int nums[6] = {0,1,2,3,4,5};

Arrays can be created for any data type but each element may only contain data of the same data type. Collectively elements in an array is known as an β€œindex”. Arrays can have more than one index.

So whenever you create a variable in C++, you must tell the complier the variable’s name and the variable’s data type (e.g integer, character, floating-point). A variable has three aspects that needs to be checked: name, type, value.

What’s in a Name? Aspect #1.

The name of a variable is known as its identifier. Every variable must have a name, but must adhere to the naming conventions where the chosen name may contain letters, digits, and the underscore character but cannot begin with the digit.(It’s best not to use underscore for portability ).

Case Sensitivity
Whether you use uppercase or lowercase letters really matters. Names are very case-sensitive in C++ from keywords to functions to variables, they are all case-sensitive.

a Rose, is not a rose, is not a ROSE 🌹

Scope.
Before the ruling of the scope is that a variable cannot be used in any part of the program before it is defined. A variable scope is limited to the part of the program that has access to the variable. Local, global and so on.

Global Scopeinclude <iostream>
using namespace std;
int x; // Global variable declared
int main()
{
x=10; // Initialized once
cout <<"first value of x = "<< x;
x=20; // Initialized again
cout <<"Initialized again with value = "<< x;
}
--------------------------------------------------Local Scopeinclude <iostream>
using namespace std;
int main()
{
int i=10;
if(i<20) // if condition scope starts
{
int n=100; // Local variable declared and initialized
} // if condition scope ends
cout << n; // Compile time error, n not available here
}

Keywords
Keywords must be avoided when naming constants, variables or any other identifier’s name.

Keywords
╔════════════╦═══════════╦═════════════════╦═══════════╗
β•‘asm β•‘ else β•‘ new β•‘ this β•‘
β•‘auto β•‘ enum β•‘ operator β•‘ throw β•‘
β•‘bool β•‘ explicit β•‘ private β•‘ true β•‘
β•‘break β•‘ export β•‘ protected β•‘ try β•‘
β•‘case β•‘ extern β•‘ public β•‘ typedef β•‘
β•‘catch β•‘ false β•‘ register β•‘ typeid β•‘
β•‘char β•‘ float β•‘ reinterpret_castβ•‘ typename β•‘
β•‘class β•‘ for β•‘ return β•‘ union β•‘
β•‘const β•‘ friend β•‘ short β•‘ unsigned β•‘
β•‘const_cast β•‘ goto β•‘ signed β•‘ using β•‘
β•‘continue β•‘ if β•‘ sizeof β•‘ virtual β•‘
β•‘default β•‘ inline β•‘ static β•‘ void β•‘
β•‘delete β•‘ int β•‘ static_cast β•‘ volatile β•‘
β•‘do β•‘ long β•‘ struct β•‘ wchar_t β•‘
β•‘double β•‘ mutable β•‘ switch β•‘ while β•‘
β•‘dynamic_castβ•‘ namespace β•‘ template β•‘ β•‘ β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•©β•β•β•β•β•β•β•β•β•β•β•β•©β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•©β•β•β•β•β•β•β•β•β•β•β•β•

Why Specify the Type? Aspect #2

In order for a variable to be declared, it must be specify the type of data that it may contain. Why? It lets the complier know how much memory needs to be set aside to hold that variable’s value. So all in one, a variable has three aspects that needs to be checked: name, type, value. The basic syntax shown below accomplishes the first two.

Basic Syntax
VariableType VariableName;

Multiple Variables of the same data type can be created.
VariableType VariableName1, VariableName2, VariableName3;

Run the program below to see the memory size of different data types.

Quick Intro to Data Types & Modifiers

Diving into Primitives, Modifiers, TypeQualifier, TypeDef, & more before moving onto aspect #3.

Primitives Data Types
Built-in or predefined data types and can be used directly by the user to declare variables. e.g int, char , float, bool etc.

DATA TYPES (Primitive)
╔══════════╦════════════════╦══════════════════════╦═══════════════╗
β•‘ Keyword β•‘ Type β•‘Description β•‘ Example β•‘
╠══════════╬════════════════╬══════════════════════╬═══════════════╣
β•‘ char β•‘ character β•‘ a single byte β•‘ 'A' β•‘ ╠══════════╬════════════════╬══════════════════════╬═══════════════╣
β•‘ int β•‘ integer β•‘ a whole number β•‘ 10 β•‘
╠══════════╬════════════════╬══════════════════════╬═══════════════╣║ float β•‘ floating point β•‘ a floating number, β•‘ .0123456 β•‘ β•‘ β•‘ β•‘ correct to 6 numbers β•‘ β•‘ ╠══════════╬════════════════╬══════════════════════╬═══════════════╣
β•‘ double β•‘ double floatingβ•‘ a floating number, β•‘ .0123456789 β•‘
β•‘ β•‘ point β•‘correct to 10 numbers β•‘ β•‘
╠══════════╬════════════════╬══════════════════════╬═══════════════╣
β•‘ bool β•‘ boolean β•‘ check the state β•‘ true or false β•‘ β•‘ β•‘ β•‘ of a variable β•‘ 0 or 1 β•‘ ╠══════════╬════════════════╬══════════════════════╬═══════════════╣║ void β•‘ valueless β•‘ W/o any value β•‘ β•‘
╠══════════╬════════════════╬══════════════════════╬═══════════════╣ β•‘ wchar_t β•‘ wide character β•‘ size greater than theβ•‘ β•‘
β•‘ β•‘ β•‘ normal 8-bit datatypeβ•‘ β•‘
β•šβ•β•β•β•β•β•β•β•β•β•β•©β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•©β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•©β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•
More exampleschar a = 'A'; // character type
int a = 1; // integer type
float a = 3.14159; // floating point type
double a = 6e-4; // double type (e is for exponential)

Data Types Modifiers
There are four datatype modifiers: signed, unsigned, long, short. The datatype modifiers are used with the built-in data types to modify the length of data that a particular data type can hold, except for type void.

Data Types (Modifiers)
╔════════════════╦══════════════╦════════════════╗
β•‘ short β•‘ int β•‘ long β•‘
β•‘ unsigned short β•‘ unsigned int β•‘ unsigned long β•‘
β•‘ signed short β•‘ signed int β•‘ signed long β•‘
β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•©β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•©β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•
Note short is short name for short int
Note long is short name for long int.

What are the rules for assigning variable with the above data types?

  • Assign short, int or long data types when you are sure a variable is an integer number (NO decimal points). While these three integer choices are available, based upon the size of the numbers you are using.
  • Assign float or double when decimals are needed.
  • Assign char if the variable will always contain ONE character of data. This means only one letter (or character).

Data Types Modifiers
Be used along with built in datatypes to make them more precise and even expand their range.

Data Types (Modifiers by Categories)
╔════════════════╦════════════════╦════════════════╗
β•‘ Integer Type β•‘ Character Type β•‘ Floating-Point β•‘ β•‘ Example β•‘ Modifier β•‘ Type Modifiers β•‘
╠════════════════╬════════════════╬════════════════╣
β•‘ short β•‘ char β•‘ float β•‘
β•‘ unsigned short β•‘ unsigned char β•‘ double β•‘
β•‘ signed int β•‘ signed char β•‘ long double β•‘
β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•©β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•©β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•

Integer Type Modifiers
Offers three types of integers: short, int, and long that can represent up to three different integer sizes.

  • Unsigned, numbers are always positive.
  • Unsigned type are used for quantities that are never negative such as populations, sports, scores, inventory, etc.
  • Signed types includes both positive and negative numbers and is the default type.
  • Size hierarchy: short int < int < long int

Character Type Modifiers
Large enough to represent the entire range of basic symbols β€” all the letters, digits, punctuation and the like β€” for the target computer system.

  • char is neither signed nor unsigned by default, unlike int.
  • holds numbers i.e characters/symbols
  • unsigned char range(0–256)
  • signed char range (-128 to 127)

Floating Point Type Modifiers
Have three floating types : float, double, and long double. A float allows you to store decimal values that would be declared in the following.

float pi = 3.14;
double morePrecisePi= 22.0 / 7;
  • double precision float is simply called a double.
  • long float is not a legal type.
  • there are no short floating point numbers.
  • Size Hierarchy : float < double < long double

Type Qualifiers in C++
The type qualifiers can help provide additional information about the variables they precede.

╔═══════════╦═══════════════════════════════════════════════╗
β•‘ const β•‘ Objects of type const cannot be changed β•‘
β•‘ β•‘ by your program during execution β•‘
╠═══════════╬═══════════════════════════════════════════════╣
β•‘ restrict β•‘ a pointer qualified is initially the only β•‘
β•‘ β•‘ means by which the object it points to can β•‘
β•‘ β•‘ be accessed. β•‘
╠═══════════╬═══════════════════════════════════════════════╣
β•‘ volatile β•‘ the modifier volatile tell the compiler that β•‘
β•‘ β•‘ a variable value maybe changed in ways not β•‘
β•‘ β•‘ explicit specified by the program β•‘ β•šβ•β•β•β•β•β•β•β•β•β•β•β•©β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•

Constants
A constant is a named memory location which temporarily stores data that remains the same throughout the execution of the program. Define a variable as a constant. Use the keyword β€˜const’ to define a constant.

*Should not change a single thing because that variable cannot be changed during the program. You should be receiving this error: cannot assign to variable β€˜benchGoal’ with const-qualified type β€˜const int’ and such.*

Enumerated Constants
This means that programmer can create a new variable type and then assign a finite number of values to it. What purpose does this serve? When you need a type of variable whose values are restricted by a certain set.

//Use the keyword β€˜const’ to define a constant.enum RainbowColor
{
Violet = 0;
Indigo,
Blue,
Green,
Yellow,
Orange,
Red
};

Another example has β€œenum variable” has 12 possible values.

enum MONTH {Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec};

BTW, Use a singular name for the enum. e.g MONTH instead of MONTHS.

Another way to understand this is using a compass example.

#include <iostream>
using namespace std;
int main()
{
// set up the enumeration
enum Direction {North, Northeast, East, Southeast, South, Southwest, West, Northwest };
//create a variable to hold the it
Direction heading;
heading = Southeast;
cout << "Moving " << heading;
return 0;
}

TypeDef
You can also define your own name for a built in data type. You have to at least use the keyword typedef.

typedef double MyDouble;double dAmount;
MyDouble dAmount; //Same like 'double dAmount;'

Aspect #3: Value.

A variable can be given a value through an assignment statement.

unsigned int highScore;
highScore = 3000;

Congrats you learned a lot more about variables, constants, and data types ! The biggest challenge with variables comes with choosing the proper data type. Remember to keep in mind when working with variables, the number of bytes differs by data type.

Next we will be focusing more on using expression, statements, operators.

If you enjoy this, don’t miss the other articles in this order.

  1. [Intro to C++ : Your First Program]
  2. [Intro to C++ : Variables, Constants, & Data Types]
  3. [Intro to C++ : Using Expressions, Statements and Operators]
  4. [Intro to C++: Managing Arrays & Strings]

CyberCode Twins πŸ‘Ύ πŸ‘Ύ

Written by

#TEDx SpeakersπŸŽ™οΈ| M.I.T Media Lab BC Alumni ⛓️| Top 5 IBM #SmartCities Finals πŸŒ‡ | πŸš€PR πŸ‡΅πŸ‡· LA | #TwitchDev #Blockchain #AI| CyberCodeTwins.com | shEOS.org

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium β€” and support writers while you’re at it. Just $5/month. Upgrade