Login(Email) Password Forget Password? Account Settings
Home ASP.net System Info C# Books Java Script Visual C++(MFC) C/C++ Win API Java Contact Us
Variables and Constants
A variable is a named memory location which temporarily stores data that can change while the program is running
A constant is a named memory location which temporarily stores data that remains the same throughout the execution of the program
The type of a variable indicates what kind of value it will store.
The name of a variable is known as its identifier
A variable can be given a value through an assignment statement
C++ recognizes eleven built-in data types which are designated by reserved words:
char int
short long
float double double
long double unsigned char
unsigned int unsigned short
unsigned long
Variables of different types occupy different amounts of memory space and are described as having different sizes.
Data Type  C++ Keyword  Stores  Bytes of Memory  Range of Values
Character char 1 character 1   1 character
Short integer  short   Integers  2 -32,768 to 32,767
Integer  int  Integers 4   -2,147,483,648 to 2,147,483,647
Long Integer   long  Integers 4 -2,147,483,648 to 2,147,483,647
Float float  Decimal values to 7 decimal digit precision   4 3.4e-38 to 3.4e38
 positive and negative
Double double Decimal values to 15 decimal digit precision  8 1.7e-308 to 1.73e308
 positive and negative
Rules for assigning variables

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, we will be using only int.
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).

Naming Rules for Variables
The names of variables in the C++ language are referred to as identifiers. The best naming convention is to choose a variable name that will tell the reader of the program what the variable represents. Variables that describe the data stored at that particular memory location are called mnemonic variables.
Rules for naming variables:
  • Variable names in Visual C++ can range from 1 to 255 characters. To make variable names portable to other environments stay within a 1 to 31 character range.
  • All variable names must begin with a letter of the alphabet or an underscore( _ ). For beginning programmers, it may be easier to begin all variable names with a letter of the alphabet.
  • After the first initial letter, variable names can also contain letters and numbers. No spaces or special characters, however, are allowed.
  • Uppercase characters are distinct from lowercase characters. Using all uppercase letters is used primarily to identify constant variables.
  • You cannot use a C++ keyword (reserved word) as a variable name.
Tip: Some programmers use an underscore in variable names to separate parts of the name, such as shipping_weight. Others prefer a "capital style" notation, such as shippingWeight to separate parts of the name. NEVER use uppercase for every letter in a variable name, because uppercase names are reserved for constant variables.
Declaring Variables
All variables must be declared before they can be used.
How to declare a variable:
1. Choose the "type" you need.
2. Decide upon a name for the variable.
3. Use the following format for a declaration statement:
               datatype variable identifier; 
4. You may declare more than one variable of the same type by separating the variable names with commas.
                int age, weight, height;
5. You can initialize a variable (place a value into the variable location) in a declaration statement.
                  double mass = 3.45;

Important Note: Variables that are not initialized are NOT empty. If you do not initialize your variables, they will contain junk ("garbage") values left over from the program that last used the memory they occupy, until such time as the program places a value at that memory location
Constant Variables
Using const you can define variables whose values never change. You MUST assign an initial value into a constant variable when it is declared. If you do not place this initial value, C++ will not allow you to assign a value at a later time. Constants cannot be changed within a program.


     const int ageLimit = 21; //this value cannot be changed
C++ will allow you to declare a variable anywhere in the program as long as the variable is declared before you use it. A good programming practice to develop is to declare variables at the top of a function.

Declaring variables in this manner makes for easier readability of the program
Placing Data in Variables
The equal sign (=) is used for assigning values to variables.
The format of an assignment is:

variable = expression;
The variable is a variable name that you defined in the program. The expression is any variable, numerical, literal, or expression that produces a data type that is the same as the variable's data type.

Data may be placed in a variable when it is declared:
int grade = 98;

or data may be placed in a variable AFTER it has been declared
(at a point further down in the program):
int grade;
...
grade = 98;

Never put commas in numerical values that you assign to variables. 
The following statement is invalid:
 double sales = 87,463.95;    //Don't do this!!!!
 

Are computers and mathematicians always speaking the same language?

A computer does not interpret an equal sign in the same manner that mathematicians do.  To a computer, the equal sign means that you want to take the number, variable, or expression on the right side of the equal sign and put it into the variable on the left.

A computer understands:
grade = 98;
but a computer does not understand
98 = grade;


The statementx = x + y; may look mathematically incorrect, but to a computer it means "take what was stored inx, addy to that value, and place the answer back in x".  Remember that what is on the right side will be STORED in the variable on the left.

Mathematician:
i = i + 1

  "NO way!!"
Computer:

       "Way cool!!"

Answer:  While they agree on concepts, they do not necessarily agree on syntax (the manner in which the concepts are expressed).

Compound Operators:

C++ has its own shortcut syntax involving the placement of values into numerical variables.  You should be able to recognize all possible codings.

x += y;  is the same as  x = x + y;
x -= y;  is the same as  x = x - y;
x *= y;  is the same as  x = x * y;
x /= y;  is the same as 
x = x / y;
   x %= y;  is the same as  x = x % y;

While a powerful tool used to update variables, compound operators can be troublesome.  In the order of operations, the compound operators have lower precedence than regular math operators.  Check out these two examples:

int x = 42;
int value = 0;
value = value - x + 2;
cout<< value;  //gives - 40 
int x = 42;
int value = 0;
value -= x + 2;
cout<<value;   //gives - 44

Be careful when using compound operators.  Remember the operator precedence. 

Primary Math Operator
+ Addition
- Substraction
* Multiplication
/ Division
% Modulus (also called remainder) when using this operator both operand must be integer
There is no Exponent operator in C/C++. For that you can use pow() built in function. Example:
#include < math.h>
#include < iostream.h>
void main()
{
double x=2.0;
double y=3.0;
cout<<pow(x,y); // this will return value as y power of x.
}
Confusing Diviosns:Be careful when performing integer division. When dividing an integer by an integer, the answer will be an integer (not rounded). Compare these divisions: (5 is an integer while 5.0 is a double)

Integer division   8 / 5 =        1
Double division   8.0 / 5.0 = 1.6
Mixed division    8.0 / 5 =      1.6

When an operation involves two types (as the mixed division shown above), the smaller type is converted to the larger type. In the case above, the integer 5 was converted to a double type before the division occurred.
Printing Variables
The cout statement may be used to print the information stored in any variable location to the screen. It is possible to intermix several types of variables into one cout statement as seen below:
int num1 = 4;
double num2 = 6.5;
cout << num1 << " and also " << num2 << endl;
You can aslo write above statemet as follows for easy reading
cout << num1
        << " and also "
        << num2
        << endl;
Formatting Output


The manipulators discussed on this page require the header file named iomanip.h
#include <iostream.h>
#include <iomanip.h>

Formatting output is important in the development of output screens which can be easily read and understood.  C++ offers the programmer several input/output manipulators.  Two of these I/O manipulators are setw( ) and setprecision( )

The setw( ) manipulator sets the width of the field assigned for the output.  It takes the size of the field (in number of characters) as a parameter. 

For example, the code:    cout << setw(6) <<"R";
generates the following output on the screen (each underscore represents a blank space)

_ _ _ _ _R


The setw( ) manipulator does not stick from one cout statement to the next.  For example, if you want to right-justify three numbers within an 8-space field, you will need to repeat setw( ) for each value:
cout << setw(8) << 22 << "\n";
cout << setw(8) << 4444 << "\n";
cout << setw(8) << 666666 << endl;

The output will be (each underscore represents a blank space)
_ _ _ _ _ _ 2 2
_ _ _ _ 4 4 4 4
_ _ 6 6 6 6 6 6

The setprecision( ) manipulator sets the total number of digits to be displayed when floating point numbers are printed.

For example, the code:    cout << setprecision(5) << 123.456;
will print the following output to the screen (notice the rounding):

123.46

The setprecision( ) manipulator can also be used to set the number of decimal places to be displayed.   In order for setprecision( ) to accomplish this task, you will have to set an ios flag.  The flag is set with the following statement:

cout.setf(ios::fixed);

Once the flag has been set, the number you pass to setprecision( ) is the number of decimal places you want displayed.  The following code:

cout.setf(ios::fixed);
cout << setprecision(5) << 12.345678;

generates the following output on the screen (notice no rounding):

12.34567

Additional IOS flags:
In the statement:  cout.setf(ios::fixed);
"fixed" is referred to as a format option.

Other possible format options:

left  left-justify the output
right  right-justify the output
showpoint  display decimal point and trailing zeros for all floating point numbers, even if the decimal places are not needed.
uppercase display the "e" in E-notation as "E" rather than "e"
showpos display a leading plus sign before positive values
scientific display floating point numbers in scientific ("E") notation
fixed display floating point numbers in normal notation - no trailing zeroes and no scientific notation

**Note: You can remove these options by replacing setf with unsetf.

Displaying Amounts of Money: 
To get 5.8 to display as 5.80, the following lines of code are needed"

//display money

cout.setf(ios::fixed); 
cout.setf(ios::showpoint);    cout << setprecision(2);     

cout << 5.8

All subsequent couts retain the precision set with the last setprecision( ). Setprecision( ) is "sticky."  Whatever precision you set, sticks with the cout device until such time as you change it with an additional setprecision( ) later in the program.
Differences between #define and the const type qualifier
  • The #define directive can be used to create a name for a numerical, character, or string constant, whereas a const object of any type can be declared.
  • A const object is subject to the scoping rules for variables, whereas a constant created using #define is not.
  • Unlike a const object, the value of a macro does not appear in the intermediate source code used by the compiler because they are expanded inline. The inline expansion makes the macro value unavailable to the debugger.
  • A macro can be used in a constant expression, such as an array bound, whereas a const object cannot(only in C)
  •  C++ The compiler does not type-check a macro, including macro arguments.