Sams Teach Yourself C in 21 Days

(singke) #1
The C++ Programming Language 653

BD2


The C++ Data Types ..........................................................................................


In Day 3, “Storing Information: Variables and Constants,” you learned about the C data
types. The same data types are all available in C++. In addition to the data types pre-
sented in Day 3, there are two additional data types commonly used in C++. The first is
thebooldata type. A boolis a Boolean number that is stored in a single byte. The value
of a boolis either TrueorFalse.

Remember that Falseis considered 0 andTrueis considered any other
Note number.

In addition, C++ adds the capability to package data in a format called a class. Classes
define objects in C++. Classes will be covered in detail in tomorrow’s lesson.

Declaring Variables in C++ ................................................................................


Another difference you’ll find in C++ is tied to the declaration of variables. In C, you are
only allowed to declare a variable at the beginning of any block. The most common
place to declare a variable in C is at the beginning of a function; however, it is also pos-
sible to declare a variable in other locations as long as it is at the start of a block.
In C++, you can declare a variable at any time. This means that you can wait to declare a
variable until you are ready to use it. After they are declared, basic variables will stay in
scope until the current block ends. Listing B2.4 illustrates this capability to declare a
variable at any point.

LISTINGB2.4 vars.cpp. Declaring variables in locations other than the beginning of a
block
1: //Showing variable declarations the C++ way
2: #include <iostream.h>
3:
4: int main(int argc, char* argv[])
5: {
6: char a_char = ‘x’;
7:
8: for (int ctr = 1; ctr < 10; ctr++ )
9: {
10: cout << “\nLine: “ << ctr << “ - printing the char: “ << a_char;
11: }

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

Free download pdf