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.
What's with all these variable types?
Sometimes it can be confusing to have multiple variable types when it seems like some variable types are redundant (why have integer numbers when you have floats?). 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++
To declare a variable you use the syntax "type ;". Here are some variable declaration examples:
Code:
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.
If you were watching closely, you might have seen that declaration of a variable is always followed by a semicolon (note that this is the same procedure used when you call a function).
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.
Example :
Code:
#include
using namespace std;
int main()
{
int thisisanumber;
cout<<"Please enter a number: ";
cin>> thisisanumber;
cin.ignore();
cout<<"You entered: "<< thisisanumber <<"\n";
cin.get();
}