Sams Teach Yourself C in 21 Days

(singke) #1
12:
13: char *just_for_fun = “Just For Fun!!!”;
14:
15: cout << “\n\njust_for_fun = “ << just_for_fun << “\n”;
16:
17: return 0;
18: }

Line: 1 - printing the char: x
Line: 2 - printing the char: x
Line: 3 - printing the char: x
Line: 4 - printing the char: x
Line: 5 - printing the char: x
Line: 6 - printing the char: x
Line: 7 - printing the char: x
Line: 8 - printing the char: x
Line: 9 - printing the char: x

just_for_fun = Just For Fun!!!
As you can see, this is a pretty straightforward listing. Line 8, where the ctr
variable is being declared, should be of particular interest. In a pure C program,
this listing would generate an error. In C, you would be required to declare ctrearlier, at
the beginning of the function. Declaring a variable at the beginning of a looping struc-
ture, as shown in Listing B2.4, is very common in C++. In C++, you can declare a vari-
able when you are ready to use it.
As a second example, line 13 also declares a variable,just_for_fun. This is obviously
not at the beginning of a block, nor is it at the beginning of the main()function. As you
can see, this variable is perfectly valid in C++ and prints its contents using the cout
object in the next line.
Be careful about declaring variables in the middle of a function. Although C++ allows
you to declare variables anywhere, if declare your variables at the beginning of a block,
you make it easier for others to find and understand them. This, in turn makes it easier to
debug the program.

654 Bonus Day 2

LISTINGB2.4 continued

OUTPUT

ANALYSIS

DOdeclare variables at the beginning of
blocks rather than in the middle in order
to make your programs easier to follow.

DON’Tforget that local variables take
precedence over global variables if the
same name is used.

DO DON’T


37 448201x-Bonus2 8/13/02 11:18 AM Page 654

Free download pdf