C++ Data Types
Variables
To store an item of information in a computer, the program needs to keep track of three fundamental properties.
· Where the information is stored
· What value is kept there
· What kind of information is stored
We declare variables to keep track of these properties.
Syntax:
Data_type variable_name; //declare a variable
Variable_name = value; //assign a value
Data_type variable_name = value; //declare and assign a value
e.g.: int iAge;
unsigned int uiCounter;
You can create more than one variable of the same type in one statement.
e.g.: long lSize, lWeight;
int iAge = 30, iID, iCityCode = 501;
The type used in the declaration describes the kind of information, and the variable name represents the value symbolically. The program allocates large enough memory space to hold the data. A variable can hold different values of the same data type during the execution of the program.
Naming Rules:
· The only characters you can use in names are alphabetic characters, digits and the underscore character.
· The first character in a name cannot be a digit.
· Variable names are case sensitive.
· You can’t use a C++ keyword for a name. (e.g.: void, return , main)
· C++ places no limits on the length of a name, and all characters in a name are significant.
C++ is a strongly typed language, meaning that you must declare any variable before it is used in the program.
e.g.:
#include <iostream>
using namespace std;
int main()
{
int iIntValue = INT_MAX; //initialize iIntvalue to max int value
cout << "int takes " <<"\n";
cout << "int takes " <<"\n";
cout << "The max int value is "<<"\n";
return 0;
INT_MAX is a symbol defined in limits.h file and represents the largest possible value that an int can take. sizeof() function (defined in the compiler) takes either the data type or variable name and returns the number of bytes it occupies in the memory.
The output would be something similar to the following. (Exact values might vary with the system you are using)
int takes 4 bytes
int takes 4 bytes
The max int value is 2147483647
C++ allows you to create aliases for data types. We use the typedef keyword to do so.
Syntax: typedef type type_name;
typedef unsigned short int USHORT;
Now you can use USHORT instead of unsigned short int.
e.g.: USHORT usMyVariable;
No comments:
Post a Comment