Home

Operators and Operands

 

Unary Operators

 

Introduction

An operation is an action performed on one or more variables either to modify the value held by one or both of the variables or to produce a new value by combining variables. Therefore, an operation is performed using at least one symbol and one variable. The symbol used in an operation is called an operator. A variable or a value involved in an operation is called an operand.

A unary operator is one that uses only one operand.

An operator is referred to as binary if it operates on two operands.

Unary Operators: The Positive Operator +

 

Algebra uses a type of ruler to classify numbers. This ruler has a middle position of zero. The numbers on the left side of the 0 are considered negative while the numbers on the right side of the rulers are considered positive:

-∞   -6 -5 -4 -3 -2 -1 0 1 2 3 4 5 6   +∞
   
-∞   -6 -5 -4 -3 -2 -1 0 1 2 3 4 5 6   +∞

A value on the right side of 0 is considered positive. To express that a number is positive, you can write a + sign on its left. Examples are +4, +228, +90335. In this case the + symbol is called a unary operator because it acts on only one operand.

The positive unary operator, when used, must be positioned on the left side of its operand.

As a mathematical convention, when a value is positive, you do not need to express it with the + operator. Just writing the number without any symbol signifies that the number is positive. Therefore, the numbers +4, +228, and +90335 can be, and are better, expressed as 4, 228, 90335. Because the value does not display a sign, it is referred as unsigned as we learned in the previous lesson.

To express a variable as positive or unsigned, you can just type it. here is an example

//---------------------------------------------------------------------------
#include <iostream>
#include <conio>
using namespace std;
#pragma hdrstop

//---------------------------------------------------------------------------

#pragma argsused
int main(int argc, char* argv[])
{
    int Number = +550;
    cout << "Number = " << Number;

    cout << "\nPress any key to continue...";
    getch();
    return 0;
}
//---------------------------------------------------------------------------

This would produce:

Number = 550
Press any key to continue...

Unary Operators: The Negative Operator -

 

As you can see of the above ruler, in order to express any number on the left side of 0, it must be appended with a sign, namely the - symbol. Examples are -12, -448, -32706. A value accompanied by - is referred to as negative.

The - sign must be typed on the left side of the number it is used to negate.

Remember that if a number does not have a sign, it is considered positive. Therefore, whenever a number is negative, it must have a - sign. In the same way, if you want to change a value from positive to negative, you can just add a - sign to its left.

Here is an example that uses two variables. One has a positive value while the other has a negative value:

//---------------------------------------------------------------------------
#include <iostream>
#include <conio>
using namespace std;
#pragma hdrstop

//---------------------------------------------------------------------------

#pragma argsused
int main(int argc, char* argv[])
{
    int Number1 = 550;
    int Number2 = -48;

    cout << "First Number:  " << Number1 << endl;
    cout << "Second Number: " << Number2 << endl;

    cout << "\nPress any key to continue...";
    getch();
    return 0;
}
//---------------------------------------------------------------------------

This would produce:

First Number:  550
Second Number: -48

Press any key to continue...

Unary Operators: Increment and Decrement ++ and --

 

The increment operator is used to increase the value of a number or variable by 1. The increment operator is performed with the ++ operator. Because it involves a few more other issues, we will study it later on.

The decrement operator is used to decrease the value of a number or variable by 1. The decrement operator is performed with the -- operator. Because it involves a few more other issues, we will study it later on.

Unary Operators: The Address Operator &

 

In the previous lesson, we learned that, when declaring a variable, the compiler reserves an amount of space in memory for that variable. C++ provides an operator that can tell you where (the space for) a variable is located. This is done using the address operator represented by the ampersand &.

To get the address of a variable, use the ampersand operator on its left. The address is a hexadecimal number. Here is an example:

//---------------------------------------------------------------------------
#include <iostream>
#include <conio>
using namespace std;
#pragma hdrstop

//---------------------------------------------------------------------------

#pragma argsused
int main(int argc, char* argv[])
{
    int Number = 28;

    cout << "&Number = " << &Number;

    cout << "\nPress any key to continue...";
    getch();
    return 0;
}
//---------------------------------------------------------------------------

This would produce:

&Number = 1245064
Press any key to continue...

Unary Operators: The Reference Operator &

 

A reference is a variable name that is a duplicate of an existing variable. It provides a technique of creating more than one name to designate the same variable. To declare a reference variable, you use the reference operator expressed with the ampersand. The syntax of creating or declaring a reference is:

DataType &RefernceName = VariableName;

To declare a reference, type the variable’s name preceded by the same type as the variable it is referring to. Between the data type and the reference name, type the ampersand operator “&”. To specify what variable the reference is addressed to, use the assignment operator “=” followed by the name of the variable. The referred to variable must exist already. You cannot declare a reference as:

int &Mine;

The compiler wants to know what variable you are referring to. Here is an example:

//---------------------------------------------------------------------------
#include <iostream>
#include <conio>
using namespace std;
#pragma hdrstop

//---------------------------------------------------------------------------

#pragma argsused
int main(int argc, char* argv[])
{
    int Number = 228;
    int &Nbr = Number;

    cout << "\nPress any key to continue...";
    getch();
    return 0;
}
//---------------------------------------------------------------------------

The ampersand operator between the data type and the reference can assume one of three positions as follows:

int&  Nbr;
int & Nbr;
int  &Nbr;

As long as the & symbol is between a valid data type and a variable name, the compiler knows that the variable name (in this case Nbr) is a reference.

Once a reference has been initialized, it holds the same value as the variable it is pointing to. You can then display the value of the variable using either of both:

//---------------------------------------------------------------------------
#include <iostream>
#include <conio>
using namespace std;
#pragma hdrstop

//---------------------------------------------------------------------------
#pragma argsused

//---------------------------------------------------------------------------
int main(int argc, char* argv[])
{
    int Number = 228;
    int & Nbr = Number;

    cout << "Number = " << Number << "\n";
    cout << "Its reference = " << Nbr << "\n\n";

    cout << "\nPress any key to continue...";
    getch();
    return 0;
}
//---------------------------------------------------------------------------

If you change the value of the variable, the compiler updates the value of the reference so that both variables would hold the same value. In the same way, you can modify the value of the reference, which would update the value of the referred to variable. To access the reference, do not use the ampersand operator; just the name of the reference is sufficient to the compiler. This is illustrated in the following:

//---------------------------------------------------------------------------
#include <iostream>
#include <conio>
using namespace std;
#pragma hdrstop

//---------------------------------------------------------------------------
#pragma argsused

//---------------------------------------------------------------------------
int main(int argc, char* argv[])
{
    int Number = 228; // Regular variable
    int& Nbr = Number; // Reference 

    cout << "Number = " << Number << "\n";
    cout << "Its reference = " << Nbr << "\n";

    // Changing the value of the original variable
    Number = 4250;
    cout << "\nNumber = " << Number;
    cout << "\nIts reference = " << Nbr << "\n";

    // Modifying the value of the reference 
    Nbr = 38570;
    cout << "\nNumber = " << Number;
    cout << "\nIts reference = " << Nbr << "\n";

    cout << "\nPress any key to continue...";
    getch();
    return 0;
}
//---------------------------------------------------------------------------

This would produce:

Number = 228
Its reference = 228

Number = 4250
Its reference = 4250

Number = 38570
Its reference = 38570

Press any key to continue...

In the same way, you can use either a reference or the variable it is referring to, to request the variable’s value from the user. Here is an example:

//---------------------------------------------------------------------------
#include <iostream>
#include <conio>
using namespace std;
#pragma hdrstop

//---------------------------------------------------------------------------
#pragma argsused

//---------------------------------------------------------------------------
int main(int argc, char* argv[])
{
    double Price;
    double& RefPrice = Price;

    cout << "What's the price? $";
    cin >> Price;
    cout << "Price = $" << Price << "\n";
    cout << "Same as: $" << RefPrice << "\n\n";
    cout << "What's the price? $";
    cin >> RefPrice;

    cout << "Price = $" << Price << "\n";
    cout << "Same as: $" << RefPrice << "\n";

    cout << "\nPress any key to continue...";
    getch();
    return 0;
}
//---------------------------------------------------------------------------

Here is an example of running the program:

What's the price? $150.55
Price = $150.55
Same as: $150.55

What's the price? $2450.50
Price = $2450.5
Same as: $2450.5

Press any key to continue...

Unary Operators: The sizeof Operator

 

We have already seen that when declaring a variable, the compiler reserves a portion of memory in the computer memory to hold that variable. We also illustrated how much space some data types need to store their variable. C++ provides the unary sizeof operator that allows you to find out how much space a data type or a certain variable in your program is using. 

There are two methods you can use with the sizeof operator: using the variable or the data type. The general syntaxes of the sizeof operator are:

sizeof VariableName;
sizeof DataType;
sizeof(VariableName);
sizeof(DataType);

Any of these two formulas is admissible. But it is good to refrain from using the data type except in rare cases that you can justify. The reason you should apply the sizeof operator on the variable is because, if you change the variable (the word “variable” means it can change throughout the program), that is, if you perform any operation on it, the sizeof operator will acknowledge that and render the right result. Some and most of the time, if you apply the sizeof operator on the data type, you might end up with a bug; if you are lucky, the program would simply not compile.

Here is an example:

//---------------------------------------------------------------------------
#include <iostream>
#include <conio>
using namespace std;
#pragma hdrstop

//---------------------------------------------------------------------------
#pragma argsused

//---------------------------------------------------------------------------
int main(int argc, char* argv[])
{
    double Period = 155.50;
    int SizeOf = sizeof Period;

    cout << "The size of Period is " << SizeOf << " bytes";

    cout << "\n\nPress any key to continue...";
    getch();
    return 0;
}
//---------------------------------------------------------------------------

This would produce:

The size of Period is 8 bytes

Press any key to continue...

Practical Learning Practical Learning: Finding the Size of an Identifier

 
  1. Create a new project using the Console Wizard
  2. In the empty section of the file, type
     
    //---------------------------------------------------------------------------
    #include <iostream>
    #include <conio>
    using namespace std;
    #pragma hdrstop
    
    //---------------------------------------------------------------------------
    #pragma argsused
    
    //---------------------------------------------------------------------------
    int main(int argc, char* argv[])
    {
        char iChar;
        unsigned char uChar;
        signed char sChar;
        int iInt;
        short int sInt;
        unsigned int uInt;
        unsigned short int uShortInt;
        long int LInt;
        unsigned long int uLongInt;
        float iFloat;
        double iDouble;
        long double lDouble;
    
        cout << "The sizeof operator used on a variable\n\n";
        cout << "Identifier\t Memory Size\n"
             << "\t\t in Bytes\n";
        cout << "----------------------------------";
        cout << "\nchar\t\t\t" << sizeof(char);
        cout << "\nunsigned char\t\t" << sizeof(unsigned char);
        cout << "\nsigned char\t\t" << sizeof(signed char);
        cout << "\nint\t\t\t" << sizeof(int);
        cout << "\nshort int\t\t" << sizeof(short int);
        cout << "\nunsigned int\t\t" << sizeof(unsigned int);
        cout << "\nunsigned short int\t" << sizeof(unsigned short int);
        cout << "\nlong int\t\t" << sizeof(long int);
        cout << "\nunsigned long int\t" << sizeof(unsigned long int);
        cout << "\nfloat\t\t\t" << sizeof(float);
        cout << "\ndouble\t\t\t" << sizeof(double);
        cout << "\nlong double\t\t" << sizeof(long double);
    
        cout << "\n\nPress any key to continue...";
        getch();
        return 0;
    }
    //---------------------------------------------------------------------------
  3. Execute the program:
     
    The sizeof operator used on a variable
    
    Identifier       Memory Size
                     in Bytes
    ----------------------------------
    char                    1
    unsigned char           1
    signed char             1
    int                     4
    short int               2
    unsigned int            4
    unsigned short int      2
    long int                4
    unsigned long int       4
    float                   4
    double                  8
    long double             10
    
    Press any key to continue...
  4. Return to Bcb and change the content of the file as follows:
     
    //---------------------------------------------------------------------------
    #include <iostream>
    #include <conio>
    using namespace std;
    #pragma hdrstop
    
    //---------------------------------------------------------------------------
    #pragma argsused
    
    //---------------------------------------------------------------------------
    int main(int argc, char* argv[])
    {
        char iChar;
        unsigned char uChar;
        signed char sChar;
        int iInt;
        short int sInt;
        unsigned int uInt;
        unsigned short int uShortInt;
        long int LInt;
        unsigned long int uLongInt;
        float iFloat;
        double iDouble;
        long double lDouble;
    
        cout << "The sizeof operator used on an identifier\n\n";
        cout << "Identifier\t Memory Size\n"
             << "\t\t in Bytes\n";
        cout << "------------------------------";
        cout << "\nchar\t\t\t" << sizeof(iChar);
        cout << "\nunsigned char\t\t" << sizeof(uChar);
        cout << "\nsigned char\t\t" << sizeof(sChar);
        cout << "\nint\t\t\t" << sizeof(iInt);
        cout << "\nshort int\t\t" << sizeof(sInt);
        cout << "\nunsigned int\t\t" << sizeof(uInt);
        cout << "\nunsigned short int\t" << sizeof(uShortInt);
        cout << "\nlong int\t\t" << sizeof(LInt);
        cout << "\nunsigned long int\t" << sizeof(uLongInt);
        cout << "\nfloat\t\t\t" << sizeof(iFloat);
        cout << "\ndouble\t\t\t" << sizeof(iDouble);
        cout << "\nlong double\t\t" << sizeof(lDouble);
    
        cout << "\n\nPress any key to continue...";
        getch();
        return 0;
    }
    //---------------------------------------------------------------------------
  5. Execute the program to see the result:
     
    The sizeof operator used on an identifier
    
    Identifier       Memory Size
                     in Bytes
    ------------------------------
    char                    1
    unsigned char           1
    signed char             1
    int                     4
    short int               2
    unsigned int            4
    unsigned short int      2
    long int                4
    unsigned long int       4
    float                   4
    double                  8
    long double             10
    
    Press any key to continue...
  6. Return to Bcb

Algebraic Operators

 

In algebra, operations are performed on numeric values:

The Addition

 

The addition is an operation used to add one number to another. For example, if you have one pen and somebody gives you another pen, then you have two pens. If you keep receiving pens, you will soon have more than you had originally. In this manner, as you add pens, the number grows. The addition gives you to ability to add things of the same nature one to another, as many as necessary, until all items have been added. Sometimes, the items are added one group to another. The concept is still the same, except that this last example is faster. For example, if you have a group of eleven students and you add 5 students to the group, you can apply the same rule by adding one student at a time. But to perform this operation faster, you should work to add groups of items to one another.

The addition is performed in mathematics using the + sign. The same sign is used in C++. The + sign is located on the left side of the Backspace key. You get it by pressing Shift and =.

To get the addition of two values, you add the first one to the other. After the addition of two values has been performed, you get a new value. This means if you add Value1 to Value2, you would write Value1 + Value2. The result is another value we could call Value3. You can also add more than two values, like a + b + c.

The order you use to add two or more values doesn't matter. This means Value1 + Value2 is the same as Value2 + Value1. In the same way a + b + c is the same as a + c + b the same as b + a + c and the same as c + b + a

In C++, you can add values you know already, or you can use values the program gets from the user.

The simplest way to add values in C++ is by performing a simple sum. Here is an example:

//---------------------------------------------------------------------------
#include <iostream>
#include <conio>
using namespace std;
#pragma hdrstop

//---------------------------------------------------------------------------

#pragma argsused
// Program used to get the sum of two values
int main(int argc, char* argv[])
{
    // Get the sum of two values
    cout << "68 + 478 = " << 68 + 478;

    cout << "\n\nPress any key to continue...";
    getch();
    return 0;
}
//---------------------------------------------------------------------------


Here is the result:

68 + 478 = 546

Press any key to continue...

You can also add some values already declared and initialized in your program. Here is an example:

//---------------------------------------------------------------------------
#include <iostream>
#include <conio>
using namespace std;
#pragma hdrstop

//---------------------------------------------------------------------------

#pragma argsused
// Program used to get the sum of two values
int main(int argc, char* argv[])
{
    int a = 68;
    int b = 478;

    // Get the sum of a and b
    cout << a << " + " << b << " = " << a + b;

    cout << "\n\nPress any key to continue...";
    getch();
    return 0;
}
//---------------------------------------------------------------------------

This would produce:

68 + 478 = 546

Press any key to continue...

You can also get the values from the user as illustrated in the following program:

//---------------------------------------------------------------------------
#include <iostream>
#include <conio>
using namespace std;
#pragma hdrstop

//---------------------------------------------------------------------------

#pragma argsused
// Program used to get the sum of two values
int main(int argc, char* argv[])
{
    int a, b, c;

    // Get the sum of a, b, and c.
    cout << "Type the first value: "; cin >> a;
    cout << "The second value: "; cin >> b;
    cout << "The last value: "; cin >> c;

    cout << a << " + " << b << " + " << c << " = " << a + b + c;

    cout << "\n\nPress any key to continue...";
    getch();
    return 0;
}
//---------------------------------------------------------------------------

Practical Learning Practical Learning: Using the Addition

 
  1. Create a new C++ project using the Console Wizard
  2. Save the project as GCS1 in a new folder called GCS1
  3. Save the unit as Main.cpp
  4. Change the file as follows:
     
    //---------------------------------------------------------------------------
    // Georgetown Cleaning Services
    #include <iostream>
    #include <conio>
    using namespace std;
    #pragma hdrstop
    
    //---------------------------------------------------------------------------
    
    #pragma argsused
    int main(int argc, char* argv[])
    {
        // Variables needed for the program
        int NumberOfShirts, NumberOfOtherItems;
    
        // Get the number of items by category
        cout << " - Welcome to Georgetown Cleaning Services -\n";
        cout << "How many shirts? ";
        cin >> NumberOfShirts;
        cout << "How many other items? ";
        cin >> NumberOfOtherItems;
    
        cout << "\nThat will be "
             << NumberOfShirts + NumberOfOtherItems
             << " items to clean.";
    
        cout << "\n\nPress any key to continue...";
        getch();
        return 0;
    }
    //---------------------------------------------------------------------------
  5. Execute the program
     
    How many shirts? 4
    How many other items? 2
    
    That will be 6 items to clean.
    
    Press any key to continue...
  6. After using the program, return to your programming environment.
  7. Instead of directly calculating the sum inside of the cout operator, you can declare another variable that would hold the result. Eventually, you can use that new value somewhere else in the program.
    As an example, change the program as follows:
     
    //---------------------------------------------------------------------------
    // Georgetown Cleaning Services
    #include <iostream>
    #include <conio>
    using namespace std;
    #pragma hdrstop
    
    //---------------------------------------------------------------------------
    
    #pragma argsused
    int main(int argc, char* argv[])
    {
        // Variables needed for the program
        int NumberOfShirts, NumberOfOtherItems;
        int TotalItems;
    
        // Get the number of item categories
        cout << " - Welcome to Georgetown Cleaning Services -\n";
        cout << "How many shirts? ";
        cin >> NumberOfShirts;
        cout << "How many other items? ";
        cin >> NumberOfOtherItems;
    
        // Calculate the total number of items
        TotalItems = NumberOfShirts + NumberOfOtherItems;
    
        cout << "\nThat will be " << TotalItems
             << " items to clean.";
    
        cout << "\n\nPress any key to continue...";
        getch();
        return 0;
    }
    //---------------------------------------------------------------------------
  8. Execute the program. You will get the same behavior:
     
    How many shirts? 5
    How many other items? 2
    
    That will be 7 items to clean.
    
    Press any key to continue...

The Subtraction

 

The subtraction operation is used to take out or subtract a value from another value. It is essentially the opposite of the addition.

The subtraction in C++ is performed with the - sign, which is between the 0 and the = keys.

Here is an example:

//---------------------------------------------------------------------------
#include <iostream>
#include <conio>
using namespace std;
#pragma hdrstop

//---------------------------------------------------------------------------

#pragma argsused
int main(int argc, char* argv[])
{
    // Values used in this program
    int Value1, Value2, Value3;

    // Get the values from the user
    cout << "Type the first number: ";
    cin >> Value1;
    cout << "Type another number: ";
    cin >> Value2;

    // Subtract the first value from the second
    Value3 = Value1 - Value2;

    cout << Value1 << " - " << Value2 << " = " << Value3;

    cout << "\n\nPress any key to continue...";
    getch();
    return 0;
}
//---------------------------------------------------------------------------

Here is an example of running the program:

Type the first number: 1450
Type another number: 288
1450 - 288 = 1162

Press any key to continue...

Here is another example of running the same program:

Type the first number: 305
Type another number: 725
305 - 725 = -420

Press any key to continue...

Unlike the addition, the subtraction is not associative. This means a - b - c is not the same as c - b - a. This is illustrated in the following program:

//---------------------------------------------------------------------------
#include <iostream>
#include <conio>
using namespace std;
#pragma hdrstop

//---------------------------------------------------------------------------

#pragma argsused
// Non-associativity of the subtraction operation
int main(int argc, char* argv[])
{
    // Addition associativity
    cout << "128 + 42 +   5 = " << 128 + 42 + 5 << endl;
    cout << "  5 + 42 + 128 = " << 5 + 42 + 128 << "\n";

    // Subtraction's non-associativity
    cout << "\n128 - 42 -   5 = " << 128 - 42 - 5;
    cout << "\n  5 - 42 - 128 = " << 5 - 42 - 128;

    cout << "\n\nPress any key to continue...";
    getch();
    return 0;
}
//---------------------------------------------------------------------------

This would produce:

128 + 42 +   5 = 175
  5 + 42 + 128 = 175

128 - 42 -   5 = 81
  5 - 42 - 128 = -165

Press any key to continue...

Notice that both operations of the addition produce the same result. In the subtraction section, the numbers follow the same order but a different operation; and the last two operations render different results.

The Multiplication

 

The multiplication allows adding one value to itself a certain number of times, set by a second value. As an example, instead of adding a value to itself in this manner: a + a + a + a, since the variable a is repeated over and over again, you could simply find out how many times a is added to itself, then multiply a by that number which, is this case, is 4. This would mean adding a to itself 4 times, and you would get the same result.

The multiplication is performed with the * sign which is typed with Shift + 8. Here is an example:

//---------------------------------------------------------------------------
// Multiplication of multiple values
#include <iostream>
#include <conio>
using namespace std;
#pragma hdrstop

//---------------------------------------------------------------------------

#pragma argsused
// Non-associativity of the subtraction operation
int main(int argc, char* argv[])
{
    float a, b;

    // Multiple of a and b.
    cout << "Type two values\n";
    cout << "First Value:  ";
    cin >> a;
    cout << "Second Value: ";
    cin >> b;

    cout << a << " * " << b << " = " << a * b;

    cout << "\n\nPress any key to continue...";
    getch();
    return 0;
}
//---------------------------------------------------------------------------

Here is an example of running the program:

Type two values
First Value:  48
Second Value: 122
48 * 122 = 5856

Press any key to continue...

Just like the addition, the multiplication is associative: a * b * c = c * b * a.

When it comes to programming syntax, the rules we learned with the addition operation also apply to the multiplication.

Practical Learning Practical Learning: Using the Multiplication

 
  1. To continue with our Georgetown Cleaning Services program, we will now get the number of shirts, followed by the number of other items. Then we will evaluate the amount the customer owes by applying the multiplication operation
    Change the Main.cpp file as follows:
     
    //---------------------------------------------------------------------------
    // Georgetown Cleaning Services
    #include <iostream>
    #include <conio>
    using namespace std;
    #pragma hdrstop
    
    //---------------------------------------------------------------------------
    
    #pragma argsused
    int main(int argc, char* argv[])
    {
        // Declare the number of items
        int NumberOfShirts,     // This is the number of shirts
            NumberOfOtherItems; // Get the number of other items
    
        // Price of items
        const double PriceShirt = 0.99;
        const double PriceOtherItems = 1.75;
    
        // Declare total prices by category
        double TotalPriceShirt, TotalPriceOther, TotalOrder;
    
        // Get the number of items
        cout << " - Welcome to Georgetown Cleaning Services -\n";
        cout << "How many shirts? ";
        cin >> NumberOfShirts;
        cout << "How many other items? ";
        cin >> NumberOfOtherItems;
    
        // Calculate the total price of each item category
        TotalPriceShirt = NumberOfShirts * PriceShirt;
        TotalPriceOther = NumberOfOtherItems * PriceOtherItems;
        TotalOrder = TotalPriceShirt + TotalPriceOther;
    
        // Display the result
        cout << "\n - Georgetown Cleaning Services -\n";
        cout << "\nFor a cleaning order of "
             << NumberOfShirts << " shirts and "
             << NumberOfOtherItems << " other items, "
             << "\nthat will be: $" << TotalOrder << "\nThanks";
    
        cout << "\n\nPress any key to continue...";
        getch();
        return 0;
    }
    //---------------------------------------------------------------------------
  2. Execute the program and test it. Here is an example:
     
    - Welcome to Georgetown Cleaning Services -
    How many shirts? 4
    How many other items? 12
    
    - Georgetown Cleaning Services -
    
    For a cleaning order of 4 shirts and 12 other items,
    that will be: $24.96
    Thanks
    
    Press any key to continue...
  3. Return to Bcb.
  4. While we are at it, let's help the clerk get the amount tended by the customer, then we can calculate the difference.
    Make the following changes to the file:
     
    //---------------------------------------------------------------------------
    // Georgetown Cleaning Services
    #include <iostream>
    #include <conio>
    using namespace std;
    #pragma hdrstop
    
    //---------------------------------------------------------------------------
    
    #pragma argsused
    int main(int argc, char* argv[])
    {
        // Declare the number of items
        int NumberOfShirts,     // This is the number of shirts
            NumberOfOtherItems; // Get the number of other items
    
        // Price of items
        const double PriceShirt = 0.99;
        const double PriceOtherItems = 1.75;
    
        // Declare total prices by category
        double TotalPriceShirt, TotalPriceOther, TotalOrder;
        double AmountTended, Difference;
    
        // Get the number of items
        cout << " - Welcome to Georgetown Cleaning Services -\n";
        cout << "How many shirts? ";
        cin >> NumberOfShirts;
        cout << "How many other items? ";
        cin >> NumberOfOtherItems;
    
        // Calculate the total price of each item category
        TotalPriceShirt = NumberOfShirts * PriceShirt;
        TotalPriceOther = NumberOfOtherItems * PriceOtherItems;
        TotalOrder = TotalPriceShirt + TotalPriceOther;
    
        // Display the result
        cout << "\n - Georgetown Cleaning Services -\n";
        cout << "\nFor a cleaning order of "
             << NumberOfShirts << " shirts and "
             << NumberOfOtherItems << " other items, "
             << "\nthat will be: $" << TotalOrder;
    
        // Get the amouont tended
        cout << "\n\nAmount tended: $";
        cin >> AmountTended;
    
        // Calculate the difference for the customer
        Difference = AmountTended - TotalOrder;
    
        // Final message
        cout << "\nThe difference is $" << Difference << "\nThanks";
    
        cout << "\n\nPress any key to continue...";
        getch();
        return 0;
    }
    //---------------------------------------------------------------------------
  5. Execute the program and test it. Here is an example:
     
    - Welcome to Georgetown Cleaning Services -
    How many shirts? 2
    How many other items? 3
    
     - Georgetown Cleaning Services -
    
    For a cleaning order of 2 shirts and 3 other items,
    that will be: $7.23
    
    Amount tended: $10
    
    The difference is $2.77
    Thanks
    
    Press any key to continue...
  6. Return to your programming environment.

The Division

 

Dividing an item means cutting it in pieces or fractions of a set value. For example, when you cut an apple in the middle, you are dividing it in 2 pieces. If you cut each one of the resulting pieces, you will get 4 pieces or fractions. This is considered that you have divided the apple in 4 parts.

Therefore, the division is used to get the fraction of one number in terms of another.

The division is performed with the forward slash /.

When performing the division, be aware of its many rules. Never divide by zero (0). Make sure that you know the relationship(s) between the numbers involved in the operation.

Here is an example:

//---------------------------------------------------------------------------
#include <iostream>
#include <conio>
using namespace std;
#pragma hdrstop

//---------------------------------------------------------------------------

#pragma argsused
int main(int argc, char* argv[])
{
    float a;

    // Get a number from the user.
    cout << "Type a number: ";
    cin >> a;
    cout << "Half of " << a << " is " << a / 2;

    cout << "\n\nPress any key to continue...";
    getch();
    return 0;
}
//---------------------------------------------------------------------------

Here is an example of running the program:

Type a number: 124
Half of 124 is 62

Press any key to continue...

The Remainder

 

The division program above will give you a result of a number with decimal values if you type an odd number (like 147), which is fine in some circumstances. Sometimes you will want to get the value remaining after a division renders a natural result. Imagine you have 26 kids at a football (soccer) stadium and they are about to start. You know that you need 11 kids for each team to start. If the game starts with the right amount of players, how many will seat and wait?

The remainder operation is performed with the percent sign (%) which is gotten from pressing Shift + 5.

Here is an example:

//---------------------------------------------------------------------------
#include <iostream>
#include <conio>
using namespace std;
#pragma hdrstop

//---------------------------------------------------------------------------

#pragma argsused
int main(int argc, char* argv[])
{
    const int Players = 26;
    int YourPlayers;

    // When the game starts, how many players will wait?.
    cout << "Out of " << Players << " players, "
         << 26 % 11 << " players will have to wait when the "
         << " football match starts.\n\n";

    // Get the new number of players
    cout << "How many players do you have today? ";
    cin >> YourPlayers;

    cout << "\nOut of " << YourPlayers << " players, "
         << YourPlayers % 11 << " players will not have a team "
         << " in the beginning.";

    cout << "\n\nPress any key to continue...";
    getch();
    return 0;
}
//---------------------------------------------------------------------------

Here is an example of running the program:

Out of 26 players, 4 players will have to wait when the  football match starts.

How many players do you have today? 18

Out of 18 players, 7 players will not have a team  in the beginning.

Press any key to continue...

C++ Operators

 

As a language, C++ is equipped with non-algebraic operators intended to perform specific operations. We will review some of these operators now; some others need intermediary concepts that we haven't studied and cannot study at this time.

Parentheses

 

Like most computer languages, C++ uses parentheses to isolate a group of items that must be considered as belonging to one entity. For example, as we will learn soon, parentheses allow a function to delimit the list of its arguments.

Parentheses can also be used to isolate an operation or an expression with regard to another operation or expression. For example, when studying the algebraic operations, we saw that the subtraction is not associative and can lead to unpredictible results. In the same way, if your operation involves various operators such as addition(s) and subtraction(s), you can use parentheses to tell the compiler how to proceed with the operations, that is, what operation should (must) be performed first. Consider the following algebraic operation:

154 - 12 + 8

The question here is to know whether you want to subtract the addition of 12 and 8 from 154 or you want to add the difference between 154 and 12 to 8. Using parentheses, you can communicate your intentions to the compiler. This is illustrated in the following program:

//---------------------------------------------------------------------------
// Using parentheses
#include <iostream>
#include <conio>
using namespace std;
#pragma hdrstop

//---------------------------------------------------------------------------

#pragma argsused
int main(int argc, char* argv[])
{
    cout << "(154 - 12) + 8  = " << (154 - 12) + 8 << "\n";
    cout << " 154 - (12 + 8) = " << 154 - (12 + 8);

    cout << "\n\nPress any key to continue...";
    getch();
    return 0;
}
//---------------------------------------------------------------------------

This would produce:

(154 - 12) + 8  = 150
 154 - (12 + 8) = 134

Press any key to continue...

As you can see, using the parentheses controls how the whole operation would proceeds This difference can be even more accentuated if your operation includes 3 or more operators and 4 or more operands.

Practical Learning Practical Learning: Using Parentheses

 
  1. To use parentheses, change the Main.cpp file as follows:
     
    //---------------------------------------------------------------------------
    // Georgetown Cleaning Services
    #include <iostream>
    #include <conio>
    using namespace std;
    #pragma hdrstop
    
    //---------------------------------------------------------------------------
    
    #pragma argsused
    int main(int argc, char* argv[])
    {
        // Declare the number of items
        int NumberOfShirts,     // This is the number of shirts
            NumberOfOtherItems; // Get the number of other items
    
        // Price of items
        const double PriceShirt = 0.99;
        const double PriceOtherItems = 1.75;
    
        double AmountTended;
    
        // Get the number of items
        cout << " - Welcome to Georgetown Cleaning Services -\n";
        cout << "How many shirts? ";
        cin >> NumberOfShirts;
        cout << "How many other items? ";
        cin >> NumberOfOtherItems;
    
        // Display the result
        cout << "\n - Georgetown Cleaning Services -\n";
        cout << "\nFor a cleaning order of "
             << NumberOfShirts << " shirts and "
             << NumberOfOtherItems << " other items, "
             << "\nthat will be: $" << (NumberOfShirts * PriceShirt) +
                                       (NumberOfOtherItems * PriceOtherItems);
    
        // Get the amouont tended
        cout << "\n\nAmount tended: $";
        cin >> AmountTended;
    
        // Final message
        cout << "\nThe difference is $"
             << AmountTended - (NumberOfShirts * PriceShirt) +
                (NumberOfOtherItems * PriceOtherItems)
             << "\nThanks";
    
        cout << "\n\nPress any key to continue...";
        getch();
        return 0;
    }
    //---------------------------------------------------------------------------
  2. Execute the program to test it. Here is an example:
     
    - Welcome to Georgetown Cleaning Services -
    How many shirts? 8
    How many other items? 4
    
     - Georgetown Cleaning Services -
    
    For a cleaning order of 8 shirts and 4 other items,
    that will be: $14.92
    
    Amount tended: $20
    
    The difference is $19.08
    Thanks
    
    Press any key to continue...
  3. Return to Bcb

Square  Brackets

 

Square brackets are mostly used to control the dimension or index of an array. We will learn how to use them when we study arrays.

Curly Brackets

 

Curly brackets are probably the most used and the most tolerant operators of C++. Fundamentally, curly brackets are used to create or isolate sections of code. As such they are required to delimit the bodies of functions, classes, structures, exceptions, and namespaces. They are also optionally used in conditional statements. Square brackets are also used to create variable scope. We will view all these uses of square brackets in this book.

Incrementing a Number

 

We are used to counting numbers such as 1, 2, 3, 4, etc. In reality, when counting such numbers, we are simply adding 1 to a number in order to get the next number in the range. C++ provides a technique of transparently counting such numbers.

The simplest technique of incrementing a value consists of adding 1 to a variable. After adding 1, the value or the variable is (permanently) modify and the variable would hold the new value. This is illustrated in the following example:

//---------------------------------------------------------------------------
#include <vcl.h>
#include <iostream.h>
#include <conio.h>
#pragma hdrstop

//---------------------------------------------------------------------------

#pragma argsused
int main(int argc, char* argv[])
{
    int Value = 12;

    cout << "Value = " << Value << endl;
    Value = Value + 1;
    cout << "Value = " << Value << endl;

    cout << "\nPress any key to continue...";
    getch();
    return 0;
}
//---------------------------------------------------------------------------

C++ provides a special operator that takes care of this operation. The operator is called the increment operator and is ++. Instead of writing Value = Value + 1, you can write Value++ and you would get the same result. The above program can be re-written as follows:

//---------------------------------------------------------------------------
#include <vcl.h>
#include <iostream.h>
#pragma hdrstop

//---------------------------------------------------------------------------

#pragma argsused
int main(int argc, char* argv[])
{
    int Value = 12;

    cout << "Value = " << Value << endl;
    Value++;
    cout << "Value = " << Value << endl;

    cout << "\nPress any key to continue...";
    getchar();
    return 0;
}
//---------------------------------------------------------------------------

The increment++ is called a unary operator because it operates on only one variable. It is used to modify the value of the variable by adding 1 to it.

Every time the Value++ is executed, the compiler takes the previous value of the variable and adds 1 to it and the variable holds the incremented value:

//---------------------------------------------------------------------------
#include <vcl.h>
#include <iostream.h>
#pragma hdrstop

//---------------------------------------------------------------------------

#pragma argsused
int main(int argc, char* argv[])
{
    int Value = 12;

    cout << "Value = " << Value << endl;
    Value++;
    cout << "Value = " << Value << endl;
    Value++;
    cout << "Value = " << Value << endl;
    Value++;
    cout << "Value = " << Value << endl;

    cout << "\nPress any key to continue...";
    getchar();
    return 0;
}
//---------------------------------------------------------------------------

 

Pre and Post-Increment

 

When using the ++ operator, the position of the operator with regard to the variable it is modifying can be significant. To increment the value of the variable before re-using it, you should position the operator on the left of the variable:

//---------------------------------------------------------------------------
#include <vcl.h>
#include <iostream.h>
#pragma hdrstop

//---------------------------------------------------------------------------

#pragma argsused
int main(int argc, char* argv[])
{
    int Value = 12;

    cout << "Value = " << Value << endl;
    cout << "Value = " << ++Value << endl;
    cout << "Value = " << Value << endl;

    cout << "\nPress any key to continue...";
    getchar();
    return 0;
}
//---------------------------------------------------------------------------

When writing ++Value, the value of the variable is incremented before being called. On the other hand, if you want to first use a variable, then increment it, in other words, if you want to increment the variable after calling it, position the ++ operator on the right side of the variable:

//---------------------------------------------------------------------------
#include <vcl.h>
#include <iostream.h>
#pragma hdrstop

//---------------------------------------------------------------------------

#pragma argsused
int main(int argc, char* argv[])
{
    int Value = 12;

    cout << "Value = " << Value << endl;
    cout << "Value = " << Value++ << endl;
    cout << "Value = " << Value << endl;

    cout << "\nPress any key to continue...";
    getchar();
    return 0;
}
//---------------------------------------------------------------------------

 

Decrementing – Pre and Post-Decrementing

 

When counting numbers backward, such 8, 7, 6, 5, etc, we are in fact subtracting 1 from a value in order to get the lesser value. This operation is referred to as decrementing a variable. This operation works as if a variable called Value has its value diminished by 1, as in

Value = Value – 1:
//---------------------------------------------------------------------------
#include <vcl.h>
#include <iostream.h>
#pragma hdrstop

//---------------------------------------------------------------------------

#pragma argsused
int main(int argc, char* argv[])
{
    int Value = 8;

    cout << "Value = " << Value << endl;
    Value = Value - 1;
    cout << "Value = " << Value << endl;

    cout << "\nPress any key to continue...";
    getchar();
    return 0;
}
//---------------------------------------------------------------------------

As done with the increment, C++ provides a quicker way of subtracting 1 from a variable. This is done using the decrement operation, that is --. To use the decrement operator, type – on the left or the right side of the variable when this operation is desired. Using the decrement operator, the above program could be written:

//---------------------------------------------------------------------------
#include <vcl.h>
#include <iostream.h>
#pragma hdrstop

//---------------------------------------------------------------------------

#pragma argsused
int main(int argc, char* argv[])
{
    int Value = 8;

    cout << "Value = " << Value << endl;
    Value--;
    cout << "Value = " << Value << endl;

    cout << "\nPress any key to continue...";
    getchar();
    return 0;
}
//---------------------------------------------------------------------------

Once again, the position of the operator is important. If you want to decrement the variable before calling it, position the operator on the left side of the operator. This is illustrated in the following program:

//---------------------------------------------------------------------------
#include <vcl.h>
#include <iostream.h>
#pragma hdrstop

//---------------------------------------------------------------------------

#pragma argsused
int main(int argc, char* argv[])
{
    int Value = 8;

    cout << "Value = " << Value << endl;
    cout << "Value = " << --Value << endl;
    cout << "Value = " << Value << endl;

    cout << "\nPress any key to continue...";
    getchar();
    return 0;
}
//---------------------------------------------------------------------------

If you plan to decrement a variable only after it has been accessed, position the operator on the right side of the variable. Here is an example:

//---------------------------------------------------------------------------
#include <iostream>
using namespace std;
#pragma hdrstop

//---------------------------------------------------------------------------

#pragma argsused
int main(int argc, char* argv[])
{
    int Value = 8;

    cout << "Value = " << Value << endl;
    cout << "Value = " << Value-- << endl;
    cout << "Value = " << Value << endl;

    cout << "\nPress any key to continue...";
    getchar();
    return 0;
}
//---------------------------------------------------------------------------

 

Techniques of Incrementing and Decrementing a Variable

 

It is not unusual to add or subtract a constant value to or from a variable. All you have to do is to declare another variable that would hold the new value. Here is an example:

//---------------------------------------------------------------------------
#include <vcl.h>
#include <iostream.h>
#pragma hdrstop

//---------------------------------------------------------------------------

#pragma argsused
int main(int argc, char* argv[])
{
    double Value = 12.75;
    double NewValue;

    cout << "Value = " << Value << endl;
    NewValue = Value + 2.42;
    cout << "Value = " << NewValue << endl;

    cout << "\nPress any key to continue...";
    getchar();
    return 0;
}
//---------------------------------------------------------------------------

The above technique requires that you use an extra variable in your application. The advantage is that each value can hold its own value although the value of the second value depends to whatever would happen to the original or source variable. Sometimes in your program you will not need to keep the value of the source variable. You might want to simply permanently modify the value that a variable is holding. In this case you can perform the addition operation directly on the variable by adding the desired value to the variable. This operation modifies whatever value a variable is holding and does not need an additional variable. To add a value to a variable and change the value that the variable is holding, use the assignment “=” and the addition “+” operators as follows:

//---------------------------------------------------------------------------
#include <vcl.h>
#include <iostream.h>
#pragma hdrstop

//---------------------------------------------------------------------------

#pragma argsused
int main(int argc, char* argv[])
{
    double Value = 12.75;

    cout << "Value = " << Value << endl;
    Value = Value + 2.42;
    cout << "Value = " << Value << endl;

    cout << "\nPress any key to continue...";
    getchar();
    return 0;
}
//---------------------------------------------------------------------------

To diminish the value of a variable, instead of the addition operation, use the subtraction and apply the same technique. In the above program, the variable can have its value decremented by applying the assignment and the subtraction operations on the variable as follows:

//---------------------------------------------------------------------------
#include <vcl.h>
#include <iostream.h>
#pragma hdrstop

//---------------------------------------------------------------------------

#pragma argsused
int main(int argc, char* argv[])
{
    double Value = 12.75;

    cout << "Value = " << Value << endl;
    Value = Value - 5.36;
    cout << "Value = " << Value << endl;

    cout << "\nPress any key to continue...";
    getchar();
    return 0;
}
//---------------------------------------------------------------------------

 

Bit Manipulations

 
 

Introduction

 

We learned in the previous lesson that, when you declare a variable, the compiler reserves an amount of space in memory for that variable. Indeed, as we learned when studying bytes and words, a declared variable occupies space that resembles a group of small boxes. In our human understanding, it is not always easy to figure out how a letter such as as B is stored in 7 seven small boxes when we know that B is only one letter.

Bit manipulation or a bit related operation allows you to control how values are stored in bits. This is not an operation you will need to perform very often, especially not in the early stages of your C++ journey. Nevertheless, bit operations (and related overloaded operators) are present on all GUI or application programming environments, so much that you should be aware of what they do or what they offer. At this time, you should (must) be aware of what a bit, byte, and a word are, as we saw in the previous lesson.

Bits Operators: The Bitwise NOT Operator ~

 

One of the operations you can perform on a bit consists of reversing its value. That is, if a bit holds a value of 1, you may want to change it to 0 and vice-versa. This operation can be taken care of by the bitwise NOT operator that is represented with the tilde symbol ~

The bitwise NOT is a unary operator that must be placed on the left side of its operand as in

~Value

To perform this operation, the compiler considers each bit that is part of the operand and inverts the value of each bit from 1 to 0 or from 0 to 1 depending on the value the bit is holding. This operation can be resumed in the following table:

Bit ~Bit
1 0
0 1

Consider a number with a byte value such as 248. In Appendix C, we define how to convert numbers from one system to another (this could be a good time to review or study Appendix C). Based on this, the binary value of decimal 248 is 1111 1000 (and its hexadecimal value is 0xF8). If you apply the bitwise NOT operator on it to reverse the values of its bits, you would get the following result:

 Value 1 1 1 1 1 0 0 0
~Value 0 0 0 0 0 1 1 1

Comparing Bits: The Bitwise AND Operator &

 

The bitwise & is a binary operator that uses the following syntax

Operand1 & Operand2

This operator considers two values and compares the bit of each with the corresponding bit of the other value. If both corresponding bits are 1, the comparison produces 1. Otherwise, that is, if either bit is 0, the comparison produces 0. This comparison is resumed as follows:

Bit1 Bit2 Bit1 & Bit2
0 0 0
1 0 0
0 1 0
1 1 1

Imagine you have two byte values represented as 187 and 242. Based on Appendix C, the binary value of decimal 187 is 1011 1011 (and its hexadecimal value is 0xBB). The binary value of decimal 242 is 1111 0010 (and its hexadecimal value is 0xF2). Let’s compare these two values bit by bit, using the bitwise AND operator:

  Binary Decimal
N1 1 0 1 1 1 0 1 1 187
N2 1 1 1 1 0 0 1 0 242
N1 & N2 1 0 1 1 0 0 1 0 178

Most of the times, you will want the compiler to perform this operation and use the result in your program. This means that you can get the result of this operation and possibly display it on the console. The above operation can be performed by the following program:

//---------------------------------------------------------------------------
#include <iostream>
#include <conio>
using namespace std;
#pragma hdrstop

//---------------------------------------------------------------------------

#pragma argsused
int main(int argc, char* argv[])
{
    const int N1 = 187;
    const int N2 = 242;

    cout << N1 << " & " << N2 << " = " << (N1 & N2) << "\n\n";

    cout << "\nPress any key to continue...";
    getch();
    return 0;
}
//---------------------------------------------------------------------------

This would produce:

187 & 242 = 178

Comparing Bits: The Bitwise OR Operator |

 

You can perform another type of comparison on bits using the bitwise OR operator that is represented by |. Its syntax is:

Value1 | Value2

Once again, the compiler compares the corresponding bits of each operand. If at least one of the equivalent bits is 1, the comparison produces 1. The comparison produces 0 only if both bits are 0. This operation is resumed as follows:

Bit1 Bit2 Bit1 | Bit2
0 0 0
1 0 1
0 1 1
1 1 1

Once again, let’s consider decimals 187 and 242. Their bitwise OR comparison would render the following result:

  Binary Decimal
N1 1 0 1 1 1 0 1 1 187
N2 1 1 1 1 0 0 1 0 242
N1 | N2 1 1 1 1 1 0 1 1 251

You can also let the compiler perform the operation and produce a result. Here is an example:

//---------------------------------------------------------------------------
#include <iostream>
#include <conio>
using namespace std;
#pragma hdrstop

//---------------------------------------------------------------------------

#pragma argsused
int main(int argc, char* argv[])
{
    const int N1 = 187;
    const int N2 = 242;
    cout << N1 << " | " << N2 << " = " << (N1 | N2);

    cout << "\n\nPress any key to continue...";
    getch();
    return 0;
}
//---------------------------------------------------------------------------

This would produce:

187 | 242 = 251

Press any key to continue...

Comparing Bits: The Bitwise-Exclusive XOR Operator ^

 

Like the previous two operators, the bitwise-exclusive OR operator performs a bit comparison of two values. It syntax is:

Value1 ^ Value2

The compiler compares the bit of one value to the corresponding bit of the other value. If one of the bits is 0 and the other is 1, the comparison produces 1. In the other two cases, that is, if both bits have the same value, the comparison produces 0. This operation is resumed as follows:

Bit1 Bit2 Bit1 ^ Bit2
0 0 0
1 0 1
0 1 1
1 1 0

We will again consider decimals 187 and 242. Their bitwise-exclusive XOR comparison would render the following result:

  Binary Decimal
N1 1 0 1 1 1 0 1 1 187
N2 1 1 1 1 0 0 1 0 242
N1 ^ N2 0 1 0 0 1 0 0 1 73

If the compiler performs this operation, it can produce a result as in the following example:

//---------------------------------------------------------------------------
#include <iostream>
#include <conio>
using namespace std;
#pragma hdrstop

//---------------------------------------------------------------------------

#pragma argsused
int main(int argc, char* argv[])
{
    const int N1 = 187;
    const int N2 = 242;

    cout << N1 << " ^ " << N2 << " = " << (N1 ^ N2);

    cout << "\n\nPress any key to continue...";
    getch();
    return 0;
}
//---------------------------------------------------------------------------

This would produce:

187 ^ 242 = 73

Press any key to continue...

Bit Shift Operators: The Left Shift <<

 

In the previous lesson, we learned that bits are aligned in some consecutive manner to store data as needed. One operation you can perform on such bits consists of moving bits in a direction of your choice.

C++ provides the left shift operator represented with << and its syntax is:

Value << ConstantInteger

The left shift operator, <<, is a binary operator whose right operand must be a constant integer. When performing the operation, the compiler would “push” Value’s bits to the left by the number of ConstantInteger. The number of ConstantInteger bits on the left side of Value would disappear. The bits on the left side of Value would replace them. After moving to the left, the space left by the most right bits would be filled with 0 bits.

Imagine you have a variable named Value and whose value is 42. The binary value of 42 is 0010 1010 (you are probably asking, "Why the hell do I need to know this?" and my answer is, "I have no idea" but you ain't got no choice; ain't no one else gonna learn this stuff for you). Imagine you want to shift Value to the left by 2 bits. You would proceed as follows:

    0 0 1 0 1 0 1 0
42 Shifted to the left by 2 bits << 2
0 0 1 0 1 0 1 0 0 0

The resulting binary number is 1010 1000 and its decimal value is  1*27 + 0*26 + 1*25 + 0*24 + 1*23 + 0*22 + 0*21 + 0*20 = 1*128 + 0*64 + 1*32 + 0*16 + 1*8 + 0*4 + 0*2 + 0*1 = 128 + 0 + 32 + 0 + 8 + 0 + 0 + 0 = 128 + 32 + 8 = 168

This can also be illustrated in the following program:

//---------------------------------------------------------------------------
#include <iostream>
#include <conio>
using namespace std;
#pragma hdrstop

//---------------------------------------------------------------------------

#pragma argsused
int main(int argc, char* argv[])
{
    const int Value = 42;

    cout << Value << " << 2 = " << (Value << 2);

    cout << "\n\nPress any key to continue...";
    getch();
    return 0;
}
//---------------------------------------------------------------------------

This would produce:

42 << 2 = 168

Bit Shift Operators: The Right Shift >>

 

As opposed to the left operator, the right shift moves bits to the right by a natural number. Everything is done as for the left shift except that the concept is applied to the opposed direction.

Therefore, if you shift 42 to the right, the binary result would be 0000 1010, whose decimal value is 10.

Variable Casting: An Introduction

 

A compiler has the duty of rendering good results, but sometimes it cannot; it might figure out what is going on in your program. This means sometimes you have to be explicit. When performing operations on variables of different types, you need to tell the compiler what form of result you are expecting. For example, you can ask the compiler to convert a variable or result from one type to another, otherwise the compiler might just "make up its own mind". And most of the time you will not like it.

Value casting consists of converting the type of data that the value is holding into another type. There are two main techniques available in C++: the old but still working C fashion and the safer C++ alternative.

C Casting

 

The C language casts a value using one of the following syntaxes:

DataType(Expression)
(DataType)Expression

Here is an example

// Examples of converting variables from and to different identifiers
//---------------------------------------------------------------------------
#include <iostream>
#include <conio>
using namespace std;
#pragma hdrstop

//---------------------------------------------------------------------------

#pragma argsused
// Variable Casting
int main(int argc, char* argv[])
{
    int i, iInt;
    char a, aChar;
    long g;
    float f;
    double d, dDouble;

    // Assign values
    i = 65;
    a = 'r';
    g = 241;
    f = 2.06;
    d = 122.448;

    cout << "The integer " << i << " converted to a character "
	<< "is " << char(i) << "\n";
    cout << "The character " << a << " converted to an integer "
	<< "is " << int(a) << "\n";
    cout << "The long integer " << g << " converted to a character "
	<< "is " << char(g) << "\n";
    cout << "The float value " << f << " converted to an integer "
	<< "is " << (int)f << "\n";
    cout << "The double value " << d << " converted to a character "
	<< "is " << (char)d << "\n";

    cout << "\n\n";

    iInt = g + i;
    aChar = i + a;
    dDouble = d + g;

    cout << "The long integer " << g << " + " << " the integer "
	<< i << " converted to an integer " << "is "
	<< int(iInt) << "\n";
    cout << "The long integer " << g << " + " << " the integer "
	<< i << " converted to a character " << "is "
	<< char(iInt) << "\n";
    cout << "The integer " << i << " + " << " the character "
	<< a << " converted to an integer " << "is "
	<< int(aChar) << "\n";
    cout << "The integer " << i << " + " << " the character "
	<< a << " converted to a character " << "is "
	<< (char)aChar << "\n";
    cout << "The integer " << i << " * " << " the character "
	<< a << " converted to an integer " << "is "
	<< double(d * a) << "\n";
    cout << "The double " << d << " / " << " the character "
	<< a << " converted to an integer " << "is "
	<< int(d / a) << "\n";
    cout << "The double " << d << " + " << " the long integer "
	<< g << " converted to an integer " << "is "
	<< (int)dDouble;

    cout << "\n\nPress any key to continue...";
    getch();
    return 0;
}
//---------------------------------------------------------------------------

This would produce:

The integer 65 converted to a character is A
The character r converted to an integer is 114
The long integer 241 converted to a character is ±
The float value 2.06 converted to an integer is 2
The double value 122.448 converted to a character is z


The long integer 241 +  the integer 65 converted to an integer is 306
The long integer 241 +  the integer 65 converted to a character is 2
The integer 65 +  the character r converted to an integer is -77
The integer 65 +  the character r converted to a character is │
The integer 65 *  the character r converted to an integer is 13959.1
The double 122.448 /  the character r converted to an integer is 1
The double 122.448 +  the long integer 241 converted to an integer is 363

Press any key to continue...

C++ Casting

 

The C++ language provides a new operator to cast the value of a certain data type to another desired and more appropriate data type. This technique can be used to perform the same casting above. This operator is called static_cast. Its syntax is:

static_cast<DesiredType>(Expression)

The static_cast keyword is required to let the compiler know that you want to perform a variable casting.

The DesiredType parameter must be a known type such as the data types we have used so far: integers, char, float, or double. It can be a reference. It can also be an enumerator. In future lessons, we will also learn that it can be a pointer or a class type. The DesiredType must be enclosed between < and >

The Expression parameter can be a value to cast. It can also be an operation or a complex expression.

Here are examples:

//---------------------------------------------------------------------------
#include <iostream>
#include <conio>
using namespace std;
#pragma hdrstop

//---------------------------------------------------------------------------

#pragma argsused
// Variable Casting
int main(int argc, char* argv[])
{
    enum TAnimalGender { sgMale, sgFemale, sgHermaphrodite, sgUnknown };
    int i, iInt, iDouble, dConvert, iChar, iConvert, iPI;
    int Gender;
    char a;
    float f;
    double d, dDouble;

    // Some values to use
    i = 65;
    a = 'r';
    f = 2.06;
    d = 122.448;

    iPI      = static_cast<int>(3.14159);
    iConvert = static_cast<int>(f);
    dConvert = static_cast<int>(d);
    iChar    = static_cast<int>(i + a);
    dDouble  = static_cast<double>(i * a);
    iDouble  = static_cast<int>(d / a);
    Gender   = static_cast<TAnimalGender>(sgHermaphrodite);

    cout << "Variable Casting";
    cout << endl << 3.14159 << " converted to an integer is " << iPI;
    cout << "\nThe float value " << f << " converted to an integer "
	<< "is " << iConvert;
    cout << "\nThe double value " << d << " converted to an integer "
	<< "is " << dConvert;
    cout << "\nThe integer " << i << " + the character "
	<< a << " converted to an integer is " << iChar;
    cout << "\nThe integer " << i << " * the character "
	<< a << " converted to a double is " << dDouble;
    cout << "\nThe double " << d << " / the character "
	<< a << " converted to an integer is " << iDouble;
    cout << "\nsgHermaphrodite of the TAnimalGender "
         << "enumerator being cast to an integer is " << Gender;

    cout << "\n\nPress any key to continue...";
    getch();
    return 0;
}
//---------------------------------------------------------------------------

This would produce:

Variable Casting
3.14159 converted to an integer is 3
The float value 2.06 converted to an integer is 2
The double value 122.448 converted to an integer is 122
The integer 65 + the character r converted to an integer is 179
The integer 65 * the character r converted to a double is 7410
The double 122.448 / the character r converted to an integer is 1
sgHermaphrodite of the TAnimalGender enumerator being cast to an integer is 2

Press any key to continue...

Operator Precedence and Direction

 

When combining operations in C++, there are two aspects involved: an operator's precedence and its direction.

If you ask a program to add two numbers, for example 240 + 65, the program will execute the operation by adding 240 to 65; in other words, it would read 240, then +, then 65, and evaluate the result. This is considered as operating from left to right: 240 -> + -> 65.

On the other hand, if you ask the program to find the size of a variable, you would write sizeof(FirstName). In this case, the program would first consider the FirstName variable, then it would evaluate the size of that variable; in other words, it first finds out the variable it is operating on, in this case FirstName. Once it knows the variable that is involved, it would execute the operation. This is considered that the operation is executed from right to left.

This process is referred to as the direction of the operation.

As you will regularly combine operators on your various calculations, each operation is known for the amount "weighs" as compared to other operators. This is known as its precedence. This means that when a certain operator is combined with another, such as a + b * c, or x / y - z, some operators would execute before others, almost regardless of how you write the operation. That's why an operator could be categorized by its level of precedence.

Refer to Appendix A for a summary list of C++ operators, their precedence and direction.

 

Previous Copyright © 2005-2012, FunctionX, Inc. Next