Programming C++  «Prev  Next»
Lesson 11 Declaration scope
Objective Rewrite the main() function of C++ program

C++ Scope Declaration and main() function

Rewrite the main() function of a C++ program so it uses a for loop instead of a do while loop. C++ allows declarations to be intermixed with executable statements. Consider a function that initializes a deck of cards to the normal 52 card values. Assume that we have already declared the card type as implemented in the previous lesson.

void init_deck(card d[])
 for (int i = 0; i < 52; ++i){
  switch (i / 13) {
   case 0: d[i].s = clubs; break;
   case 1: d[i].s = diamonds; break;
   case 2: d[i].s = hearts; break;
   case 3: d[i].s = spades; break;
  d[i].pips = 1 + i % 13;

In this function, the declaration int i occurs inside the for statement parentheses. The scope of the declaration is the innermost block within which it is found, and the identifier is visible starting at the point at which it is declared. Otherwise, the scope rules are the same as in C, which means that declarations can readily be placed near their use.

Object Declarations

Object declarations may be either inside or outside the scope of a function or class. Objects that are declared outside the scope of a function or class are called global objects. Global objects are created before the function main is called and are destroyed after the function main is exited. Generally, declaring global objects is not a good practice and should be avoided. Objects declared within a function are created when the declaration is executed and are destroyed when the block in which they are declared is exited. Objects declared in a class are created when the object (the class instance) containing them is created; they are destroyed when the object containing them is destroyed.

C++ uses notations that may appear strange to nonprogrammers. We now consider a simple program that prints a line of text below. This program illustrates several important features of the C++ language. We consider each line in detail.

// Text-printing program.
#include <iostream> // allows program to output data to the screen
// function main begins program execution
int main()
 std::cout << "Welcome to C++!\n"; // display message
 return 0; // indicate that program ended successfully
} // end function main

GCD Program Exercise

Let us get more practice writing C++ code. Click the Exercise link below to rewrite the main() function of the gcd program so it uses a for loop instead of a do while loop.
GCD Program - Exercise