Sams Teach Yourself C in 21 Days

(singke) #1

Hello C++ World! ..............................................................................................


In Day 1, you saw your first C program. This program is presented again in Listing B2.1.

LISTINGB2.1 hello.c. The C Hello World program
1: #include <stdio.h>
2:
3: int main( void )
4: {
5: printf( “Hello World!\n”);
6: return 0;
7: }

Hello World!
This listing should seem simple to you now. Your first C++ listing is just as simple.
Listing B2.2 presents the near equivalent of the C Hello World listing written in C++.

LISTINGB2.2 hello.cpp. The C++ Hello World program
1: #include <iostream.h>
2:
3: int main( void )
4: {
5: cout << “Hello C++ World!\n”;
6: return 0;
7: }

Hello C++ World!
You can see that there are only a few differences between the C++ listing and the
C listing presented in B2.1. The first difference occurs in line 1. In C++, you are
working with a different set of libraries and routines. Instead of including and linking to
standard C functions, you will link to C++ object-oriented functions and values. In line
1, you are linking to the iostream.h header file, instead of stdio.h. The iostream.h file
contains the necessary values to help you perform input and output in C++.
In line 5, you see the second big change. Instead of using a function and parenthesis, you
are using coutto send the text to the output device. coutis an object that takes care of
output for you. Rather than passing values to the coutobject, you redirect values to it.
The redirection operator (<<) is used to redirect values to cout. In this case, you can see
thatHello C++ World!is being redirected to this object. As with C statements, a semi-
colon ends C++ statement.

650 Bonus Day 2

OUTPUT

OUTPUT

ANALYSIS

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

Free download pdf