Variables in C++

Variables are reserved memory locations which are used to store various information which means that some space in memory will be reserved for that variable.

A variable of type char stores a single character, variables of type int store integers (numbers without decimal places), and variables of type float store numbers with decimal places. Each of these variable types – char, int, and float – is each a keyword that you use when you declare a variable.

Using the right variable type can be important for making your code readable and for efficiency–some variables require more memory than others. Moreover, because of the way the numbers are actually stored in memory, a float is “inexact”, and should not be used when you need to store an “exact” integer value.

Declaring Variables in C++

Here are some variable declaration examples:

int x;
char letter;
float the_float;

It is permissible to declare multiple variables of the same type on the same line; each one should be separated by a comma.

int a, b, c, d;

If you were watching closely, you might have seen that declaration of a variable is always followed by a semicolon.

Common Errors when Declaring Variables in C++

If you attempt to use a variable that you have not declared, your program will not be compiled or run, and you will receive an error message informing you that you have made a mistake. Usually, this is called an undeclared variable.

#include <iostream>

using namespace std;

int main()
{

int thisisanumber;

cout << “Please enter a number: “; cin >> thisisanumber;
cin.ignore();
cout << “You entered: ” << thisisanumber << “\n”;
cin.get();

}

Leave a Reply

Your email address will not be published. Required fields are marked *