RSS

How to use Enumerated constants in C++


Enumerated constants enable you to create new types and then to define variables of those types whose values are restricted to a set of possible values. For example, you can declare COLOR to be an enumeration, and you can define that there are five values for COLORREDBLUEGREENWHITE, andBLACK.
The syntax for enumerated constants is to write the keyword enum, followed by the type name, an open brace, each of the legal values separated by a comma, and finally a closing brace and a semicolon. Here's an example:
enum COLOR { RED, BLUE, GREEN, WHITE, BLACK };
This statement performs two tasks:
1. It makes COLOR the name of an enumeration, that is, a new type.

2. It makes RED a symbolic constant with the value 0BLUE a symbolic constant with the value 1GREEN a symbolic constant with the value 2, and so forth.
Every enumerated constant has an integer value. If you don't specify otherwise, the first constant will have the value 0, and the rest will count up from there. Any one of the constants can be initialized with a particular value, however, and those that are not initialized will count upward from the ones before them. Thus, if you write
enum Color { RED=100, BLUE, GREEN=500, WHITE, BLACK=700 };
then RED will have the value 100BLUE, the value 101GREEN, the value 500WHITE, the value 501; and BLACK, the value 700.
You can define variables of type COLOR, but they can be assigned only one of the enumerated values (in this case, REDBLUEGREENWHITE, or BLACK, or else 100101500501, or 700). You can assign any color value to your COLOR variable. In fact, you can assign any integer value, even if it is not a legal color, although a good compiler will issue a warning if you do. It is important to realize that enumerator variables actually are of type unsigned int, and that the enumerated constants equate to integer variables. It is, however, very convenient to be able to name these values when working with colors, days of the week, or similar sets of values. Listing below presents a program that uses an enumerated type.
A demonstration of enumerated constants.
1:  #include <iostream.h>
2:  int main()
3:  {
4:       enum Days { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday,                     Â_Saturday };
5:
6:       Days DayOff;
7:       int x;
8:
9:       cout << "What day would you like off (0-6)? ";
10:      cin  >> x;
11:      DayOff = Days(x);
12:
13:      if (DayOff == Sunday || DayOff == Saturday)
14:            cout << "\nYou're already off on weekends!\n";
15:      else
16:            cout << "\nOkay, I'll put in the vacation day.\n";
17:       return 0;
18: }
Output: What day would you like off (0-6)?  1

Okay, I'll put in the vacation day.

What day would you like off (0-6)?  0

You're already off on weekends!
Analysis: On line 4, the enumerated constant DAYS is defined, with seven values counting upward from 0. The user is prompted for a day on line 9. The chosen value, a number between 0 and 6, is compared on line 13 to the enumerated values for Sunday and Saturday, and action is taken accordingly.

The if statement will be covered in more detail on Day 4, "Expressions and Statements."
You cannot type the word "Sunday" when prompted for a day; the program does not know how to translate the characters in Sunday into one of the enumerated values.

  • Digg
  • Del.icio.us
  • StumbleUpon
  • Reddit
  • RSS

Demonstration of Prefix and Postfix operators in C++


Both the increment operator (++) and the decrement operator(--) come in two varieties: prefix and postfix. The prefix variety is written before the variable name (++myAge); the postfix variety is written after (myAge++).
In a simple statement, it doesn't much matter which you use, but in a complex statement, when you are incrementing (or decrementing) a variable and then assigning the result to another variable, it matters very much. The prefix operator is evaluated before the assignment, the postfix is evaluated after.
The semantics of prefix is this: Increment the value and then fetch it. The semantics of postfix is different: Fetch the value and then increment the original.
This can be confusing at first, but if x is an integer whose value is 5 and you write
int a = ++x;
you have told the compiler to increment x (making it 6) and then fetch that value and assign it to a. Thus, a is now 6 and x is now 6.
If, after doing this, you write
int b = x++;
you have now told the compiler to fetch the value in x (6) and assign it to b, and then go back and increment x. Thus, b is now 6, but x is now 7. Listing below shows the use and implications of both types.
A demonstration of prefix and postfix operators.
1:  // Listing 4.3 - demonstrates use of
2:  // prefix and postfix increment and
3:  // decrement operators
4:  #include <iostream.h>
5:  int main()
6:  {
7:      int myAge = 39;      // initialize two integers
8:      int yourAge = 39;
9:      cout << "I am: " << myAge << " years old.\n";
10:     cout << "You are: " << yourAge << " years old\n";
11:     myAge++;         // postfix increment
12:     ++yourAge;       // prefix increment
13:     cout << "One year passes...\n";
14:     cout << "I am: " << myAge << " years old.\n";
15:     cout << "You are: " << yourAge << " years old\n";
16:     cout << "Another year passes\n";
17:     cout << "I am: " << myAge++ << " years old.\n";
18:     cout << "You are: " << ++yourAge << " years old\n";
19:     cout << "Let's print it again.\n";
20:     cout << "I am: " << myAge << " years old.\n";
21:     cout << "You are: " << yourAge << " years old\n";
22:       return 0;
23: }
Output: I am      39 years old
You are   39 years old
One year passes
I am      40 years old
You are   40 years old
Another year passes
I am      40 years old
You are   41 years old
Let's print it again
I am      41 years old
You are   41 years old
Analysis: On lines 7 and 8, two integer variables are declared, and each is initialized with the value 39. Their values are printed on lines 9 and 10.
On line 11, myAge is incremented using the postfix increment operator, and on line 12, yourAge is incremented using the prefix increment operator. The results are printed on lines 14 and 15, and they are identical (both 40).
On line 17, myAge is incremented as part of the printing statement, using the postfix increment operator. Because it is postfix, the increment happens after the print, and so the value 40 is printed again. In contrast, on line 18, yourAge is incremented using the prefix increment operator. Thus, it is incremented before being printed, and the value displays as 41.
Finally, on lines 20 and 21, the values are printed again. Because the increment statement has completed, the value in myAge is now 41, as is the value in yourAge.

  • Digg
  • Del.icio.us
  • StumbleUpon
  • Reddit
  • RSS

The if Statement in C++


Normally, your program flows along line by line in the order in which it appears in your source code. Theif statement enables you to test for a condition (such as whether two variables are equal) and branch to different parts of your code, depending on the result.
The simplest form of an if statement is this:
if (expression)
     statement;
The expression in the parentheses can be any expression at all, but it usually contains one of the relational expressions. If the expression has the value 0, it is considered false, and the statement is skipped. If it has any nonzero value, it is considered true, and the statement is executed. Consider the following example:
if (bigNumber > smallNumber)
     bigNumber = smallNumber;
This code compares bigNumber and smallNumber. If bigNumber is larger, the second line sets its value to the value of smallNumber.
Because a block of statements surrounded by braces is exactly equivalent to a single statement, the following type of branch can be quite large and powerful:
if (expression)
{
     statement1;
     statement2;
     statement3;
}
Here's a simple example of this usage:
if (bigNumber > smallNumber)
{
     bigNumber = smallNumber;
     cout << "bigNumber: " << bigNumber << "\n";
     cout << "smallNumber: " << smallNumber << "\n";
}
This time, if bigNumber is larger than smallNumber, not only is it set to the value of smallNumber, but an informational message is printed. Listing below shows a more detailed example of branching based on relational operators.
A demonstration of branching based on relational operators.
1:  // Listing 4.4 - demonstrates if statement
2:  // used with relational operators
3:  #include <iostream.h>
4:  int main()
5:  {
6:        int RedSoxScore, YankeesScore;
7:        cout << "Enter the score for the Red Sox: ";
8:        cin >> RedSoxScore;
9:
10:       cout << "\nEnter the score for the Yankees: ";
11:       cin >> YankeesScore;
12:
13:       cout << "\n";
14:
15:       if (RedSoxScore > YankeesScore)
16:            cout << "Go Sox!\n";
17:
18:       if (RedSoxScore < YankeesScore)
19:       {
20:            cout << "Go Yankees!\n";
21:            cout << "Happy days in New York!\n";
22:       }
23:
24:       if (RedSoxScore == YankeesScore)
25:       {
26:            cout << "A tie? Naah, can't be.\n";
27:            cout << "Give me the real score for the Yanks: ";
28:            cin >> YankeesScore;
29:
30:            if (RedSoxScore > YankeesScore)
31:                 cout << "Knew it! Go Sox!";
32:
33:            if (YankeesScore > RedSoxScore)
34:                 cout << "Knew it! Go Yanks!";
35:
36:            if (YankeesScore == RedSoxScore)
37:                 cout << "Wow, it really was a tie!";
38:       }
39:
40:       cout << "\nThanks for telling me.\n";
41:        return 0;
42: }
Output: Enter the score for the Red Sox: 10

Enter the score for the Yankees: 10

A tie? Naah, can't be
Give me the real score for the Yanks: 8
Knew it! Go Sox!
Thanks for telling me.
Analysis: This program asks for user input of scores for two baseball teams, which are stored in integer variables. The variables are compared in the if statement on lines 15, 18, and 24.
If one score is higher than the other, an informational message is printed. If the scores are equal, the block of code that begins on line 24 and ends on line 38 is entered. The second score is requested again, and then the scores are compared again.
Note that if the initial Yankees score was higher than the Red Sox score, the if statement on line 15 would evaluate as FALSE, and line 16 would not be invoked. The test on line 18 would evaluate astrue, and the statements on lines 20 and 21 would be invoked. Then the if statement on line 24 would be tested, and this would be false (if line 18 was true). Thus, the program would skip the entire block, falling through to line 39.
In this example, getting a true result in one if statement does not stop other if statements from being tested.

  • Digg
  • Del.icio.us
  • StumbleUpon
  • Reddit
  • RSS

Advanced if Statements in C++


It is worth noting that any statement can be used in an if or else clause, even another if or elsestatement. Thus, you might see complex if statements in the following form:
if (expression1)
{
    if (expression2)
        statement1;
    else
    {
        if (expression3)
            statement2;
        else
            statement3;
    }
}
else
    statement4;
This cumbersome if statement says, "If expression1 is true and expression2 is true, execute statement1. If expression1 is true but expression2 is not true, then if expression3 is true execute statement2. If expression1 is true but expression2 and expression3 are false, execute statement3. Finally, if expression1 is not true, execute statement4." As you can see, complex if statements can be confusing!
Listing below gives an example of such a complex if statement.
A complex, nested if statement.
1:  // a complex nested
2:  // if statement
3:  #include <iostream.h>
4:  int main()
5:  {
6:      // Ask for two numbers
7:      // Assign the numbers to bigNumber and littleNumber
8:      // If bigNumber is bigger than littleNumber,
9:      // see if they are evenly divisible
10:     // If they are, see if they are the same number
11:
12:     int firstNumber, secondNumber;
13:     cout << "Enter two numbers.\nFirst: ";
14:     cin >> firstNumber;
15:     cout << "\nSecond: ";
16:     cin >> secondNumber;
17:     cout << "\n\n";
18:
19:     if (firstNumber >= secondNumber)
20:     {
21:       if ( (firstNumber % secondNumber) == 0) // evenly divisible?
22:       {
23:            if (firstNumber == secondNumber)
24:                 cout << "They are the same!\n";
25:            else
26:                 cout << "They are evenly divisible!\n";
27:       }
28:       else
29:            cout << "They are not evenly divisible!\n";
30:     }
31:     else
32:       cout << "Hey! The second one is larger!\n";
33:        return 0;
34: }

Output: Enter two numbers.
First: 10

Second: 2

They are evenly divisible!
Analysis: Two numbers are prompted for one at a time, and then compared. The first if statement, on line 19, checks to ensure that the first number is greater than or equal to the second. If not, the elseclause on line 31 is executed.
If the first if is true, the block of code beginning on line 20 is executed, and the second if statement is tested, on line 21. This checks to see whether the first number modulo the second number yields no remainder. If so, the numbers are either evenly divisible or equal. The if statement on line 23 checks for equality and displays the appropriate message either way.
If the if statement on line 21 fails, the else statement on line 28 is executed.

  • Digg
  • Del.icio.us
  • StumbleUpon
  • Reddit
  • RSS

Use of Conditional (Ternary) Operator in C++


The conditional operator (?:) is C++'s only ternary operator; that is, it is the only operator to take three terms.
The conditional operator takes three expressions and returns a value:
(expression1) ? (expression2) : (expression3)
This line is read as "If expression1 is true, return the value of expression2; otherwise, return the value of expression3." Typically, this value would be assigned to a variable.
Program below shows an if statement rewritten using the conditional operator.
A demonstration of the conditional operator.
1:   // demonstrates the conditional operator
2:   //
3:   #include <iostream.h>
4:   int main()
5:   {
6:      int x, y, z;
7:      cout << "Enter two numbers.\n";
8:      cout << "First: ";
9:      cin >> x;
10:     cout << "\nSecond: ";
11:     cin >> y;
12:     cout << "\n";
13:
14:     if (x > y)
15:       z = x;
16:     else
17:       z = y;
18:
19:     cout << "z: " << z;
20:     cout << "\n";
21:
22:     z =  (x > y) ? x : y;
23:
24:     cout << "z: " << z;
25:     cout << "\n";
26:        return 0;
27: }
Output: Enter two numbers.
First: 5

Second: 8

z: 8
z: 8
Analysis: Three integer variables are created: xy, and z. The first two are given values by the user. The if statement on line 14 tests to see which is larger and assigns the larger value to z. This value is printed on line 19.
The conditional operator on line 22 makes the same test and assigns z the larger value. It is read like this: "If x is greater than y, return the value of x; otherwise, return the value of y." The value returned is assigned to z. That value is printed on line 24. As you can see, the conditional statement is a shorter equivalent to the if...else statement.

  • Digg
  • Del.icio.us
  • StumbleUpon
  • Reddit
  • RSS

Demonstrating global and local variables in C++


Variables defined outside of any function have global scope and thus are available from any function in the program, including main().
Local variables with the same name as global variables do not change the global variables. A local variable with the same name as a global variable hides the global variable, however. If a function has a variable with the same name as a global variable, the name refers to the local variable--not the global--when used within the function. Program below illustrates these points.
Demonstrating global and local variables.
1:   #include <iostream.h>
2:   void myFunction();           // prototype
3:
4:   int x = 5, y = 7;            // global variables
5:   int main()
6:   {
7:
8:        cout << "x from main: " << x << "\n";
9:        cout << "y from main: " << y << "\n\n";
10:       myFunction();
11:       cout << "Back from myFunction!\n\n";
12:       cout << "x from main: " << x << "\n";
13:       cout << "y from main: " << y << "\n";
14:       return 0;
15:  }
16:
17:  void myFunction()
18:  {
19:       int y = 10;
20:
21:       cout << "x from myFunction: " << x << "\n";
22:       cout << "y from myFunction: " << y << "\n\n";
23: }

Output: x from main: 5
y from main: 7

x from myFunction: 5
y from myFunction: 10

Back from myFunction!

x from main: 5
y from main: 7
Analysis: This simple program illustrates a few key, and potentially confusing, points about local and global variables. On line 1, two global variables, x and y, are declared. The global variable x is initialized with the value 5, and the global variable y is initialized with the value 7.
On lines 8 and 9 in the function main(), these values are printed to the screen. Note that the functionmain() defines neither variable; because they are global, they are already available to main().
When myFunction() is called on line 10, program execution passes to line 18, and a local variable,y, is defined and initialized with the value 10. On line 21, myFunction() prints the value of the variable x, and the global variable x is used, just as it was in main(). On line 22, however, when the variable name y is used, the local variable y is used, hiding the global variable with the same name.
The function call ends, and control returns to main(), which again prints the values in the global variables. Note that the global variable y was totally unaffected by the value assigned tomyFunction()'s local y variable.

  • Digg
  • Del.icio.us
  • StumbleUpon
  • Reddit
  • RSS

Passing parameters to a function by value in C++


The arguments passed in to the function are local to the function. Changes made to the arguments do not affect the values in the calling function. This is known as passing by value, which means a local copy of each argument is made in the function. These local copies are treated just like any other local variables. Program below illustrates this point.
A demonstration of passing by value.
1:     // Demonstrates passing by value
2:
3:      #include <iostream.h>
4:
5:      void swap(int x, int y);
6:
7:      int main()
8:      {
9:        int x = 5, y = 10;
10:
11:        cout << "Main. Before swap, x: " << x << " y: " << y << "\n";
12:        swap(x,y);
13:        cout << "Main. After swap, x: " << x << " y: " << y << "\n";
14:           return 0;
15:      }
16:
17:      void swap (int x, int y)
18:      {
19:        int temp;
20:
21:        cout << "Swap. Before swap, x: " << x << " y: " << y << "\n";
22:
23:        temp = x;
24:        x = y;
25:        y = temp;
26:
27:        cout << "Swap. After swap, x: " << x << " y: " << y << "\n";
28:
29: }

Output: Main. Before swap, x: 5 y: 10
Swap. Before swap, x: 5 y: 10
Swap. After swap, x: 10 y: 5
Main. After swap, x: 5 y: 10
Analysis: This program initializes two variables in main() and then passes them to the swap()function, which appears to swap them. When they are examined again in main(), however, they are unchanged!
The variables are initialized on line 9, and their values are displayed on line 11. swap() is called, and the variables are passed in.
Execution of the program switches to the swap() function, where on line 21 the values are printed again. They are in the same order as they were in main(), as expected. On lines 23 to 25 the values are swapped, and this action is confirmed by the printout on line 27. Indeed, while in the swap()function, the values are swapped.
Execution then returns to line 13, back in main(), where the values are no longer swapped.
As you've figured out, the values passed in to the swap() function are passed by value, meaning that copies of the values are made that are local to swap(). These local variables are swapped in lines 23 to 25, but the variables back in main() are unaffected.

  • Digg
  • Del.icio.us
  • StumbleUpon
  • Reddit
  • RSS

Returning values from a function in C++


Functions return a value or return voidVoid is a signal to the compiler that no value will be returned.
To return a value from a function, write the keyword return followed by the value you want to return. The value might itself be an expression that returns a value. For example:
return 5;
return (x > 5);
return (MyFunction());
These are all legal return statements, assuming that the function MyFunction() itself returns a value. The value in the second statement, return (x > 5), will be zero if x is not greater than 5, or it will be 1. What is returned is the value of the expression, 0 (false) or 1 (true), not the value of x.
When the return keyword is encountered, the expression following return is returned as the value of the function. Program execution returns immediately to the calling function, and any statements following the return are not executed.
It is legal to have more than one return statement in a single function. Program below illustrates this idea.
A demonstration of multiple return statements.
1:     // Demonstrates multiple return
2:     // statements
3:
4:     #include <iostream.h>
5:
6:     int Doubler(int AmountToDouble);
7:
8:     int main()
9:     {
10:
11:         int result = 0;
12:         int input;
13:
14:         cout << "Enter a number between 0 and 10,000 to double: ";
15:         cin >> input;
16:
17:         cout << "\nBefore doubler is called... ";
18:         cout << "\ninput: " << input << " doubled: " << result << "\n";
19:
20:         result = Doubler(input);
21:
22:         cout << "\nBack from Doubler...\n";
23:         cout << "\ninput: " << input << "   doubled: " << result << "\n";
24:
25:
26:         return 0;
27:    }
28:
29:    int Doubler(int original)
30:    {
31:         if (original <= 10000)
32:              return original * 2;
33:         else
34:              return -1;
35:         cout << "You can't get here!\n";
36: }
Output: Enter a number between 0 and 10,000 to double: 9000

Before doubler is called...
input: 9000 doubled: 0

Back from doubler...

input: 9000   doubled: 18000

Enter a number between 0 and 10,000 to double: 11000

Before doubler is called...
input: 11000 doubled: 0

Back from doubler...
input: 11000  doubled: -1
Analysis: A number is requested on lines 14 and 15, and printed on line 18, along with the local variable result. The function Doubler() is called on line 20, and the input value is passed as a parameter. The result will be assigned to the local variable result, and the values will be reprinted on lines 22 and 23.
On line 31, in the function Doubler(), the parameter is tested to see whether it is greater than 10,000. If it is not, the function returns twice the original number. If it is greater than 10,000, the function returns -1 as an error value.
The statement on line 35 is never reached, because whether or not the value is greater than 10,000, the function returns before it gets to line 35, on either line 32 or line 34. A good compiler will warn that this statement cannot be executed, and a good programmer will take it out!

  • Digg
  • Del.icio.us
  • StumbleUpon
  • Reddit
  • RSS

Specifying default values to function parameters in C++


For every parameter you declare in a function prototype and definition, the calling function must pass in a value. The value passed in must be of the declared type. Thus, if you have a function declared as
long myFunction(int);
the function must in fact take an integer variable. If the function definition differs, or if you fail to pass in an integer, you will get a compiler error.
The one exception to this rule is if the function prototype declares a default value for the parameter. A default value is a value to use if none is supplied. The preceding declaration could be rewritten as
long myFunction (int x = 50);
This prototype says, "myFunction() returns a long and takes an integer parameter. If an argument is not supplied, use the default value of 50." Because parameter names are not required in function prototypes, this declaration could have been written as
long myFunction (int = 50);
The function definition is not changed by declaring a default parameter. The function definition header for this function would be
long myFunction (int x)
If the calling function did not include a parameter, the compiler would fill x with the default value of 50. The name of the default parameter in the prototype need not be the same as the name in the function header; the default value is assigned by position, not name.
Any or all of the function's parameters can be assigned default values. The one restriction is this: If any of the parameters does not have a default value, no previous parameter may have a default value.
If the function prototype looks like
long myFunction (int Param1, int Param2, int Param3);
you can assign a default value to Param2 only if you have assigned a default value to Param3. You can assign a default value to Param1 only if you've assigned default values to both Param2 and Param3. Program below demonstrates the use of default values.
A demonstration of default parameter values.
1:   // Demonstrates use
2:   // of default parameter values
3:
4:   #include <iostream.h>
5:
6:   int AreaCube(int length, int width = 25, int height = 1);
7:
8:   int main()
9:   {
10:       int length = 100;
11:       int width = 50;
12:       int height = 2;
13:       int area;
14:
15:       area = AreaCube(length, width, height);
16:       cout << "First area equals: " << area << "\n";
17:
18:       area = AreaCube(length, width);
19:       cout << "Second time area equals: " << area << "\n";
20:
21:       area = AreaCube(length);
22:       cout << "Third time area equals: " << area << "\n";
23:        return 0;
24:   }
25:
26:   AreaCube(int length, int width, int height)
27:   {
28:
29:       return (length * width * height);
30: }

Output: First area equals: 10000
Second time area equals: 5000
Third time area equals: 2500
Analysis: On line 6, the AreaCube() prototype specifies that the AreaCube() function takes three integer parameters. The last two have default values.
This function computes the area of the cube whose dimensions are passed in. If no width is passed in, a width of 25 is used and a height of 1 is used. If the width but not the height is passed in, aheight of 1 is used. It is not possible to pass in the height without passing in a width.
On lines 10-12, the dimensions lengthheight, and width are initialized, and they are passed to the AreaCube() function on line 15. The values are computed, and the result is printed on line 16.
Execution returns to line 18, where AreaCube() is called again, but with no value for height. The default value is used, and again the dimensions are computed and printed.
Execution returns to line 21, and this time neither the width nor the height is passed in. Execution branches for a third time to line 27. The default values are used. The area is computed and then printed.



DO remember that function parameters act as local variables within the function. DON'T try to create a default value for a first parameter if there is no default value for the second. DON'T forget that arguments passed by value can not affect the variables in the calling function. DON'T forget that changes to a global variable in one function change that variable for all functions.

  • Digg
  • Del.icio.us
  • StumbleUpon
  • Reddit
  • RSS