Вы находитесь на странице: 1из 9

The First Program

Since tradition demands it: #include <iostream> using namespace std; int main() {

C++ Basics 1

// load declarations // put 'em in scope // mandatory fn

cout << "Hello, world!" << endl; // output to console return 0; } Note: no user-defined classes #include loads declarations from standard C++ library (and more) Every C/C++ program must have a non-member fn called main(). main() must be declared with a return type of int. using directive places something within the current scope. // exit fn (& pgm)

Computer Science Dept Va Tech May 2006

Data Structures & OO Development I

2006 McQuain & Ribbens

The Preprocessor

C++ Basics 2

When a C/C++ compiler is invoked, the first thing that happens is that the code is parsed and modified by a preprocessor. The preprocessor handles a collection of commands (commonly called directives), which are denoted by the character '#'. #include directives specify an external file (for now a C/C++ library file); the preprocessor essentially copies the contents of the specified file in place of the directive. We will see more interesting preprocessor directives later.
Contents of file iostream are copied here.

#include <iostream> using namespace std; int main() { cout << "Hello, world!" << endl; return 0; }
Computer Science Dept Va Tech May 2006

Data Structures & OO Development I

2006 McQuain & Ribbens

The C++ Standard Library

C++ Basics 3

The C++ language includes a fairly large collection of types and functions. The declarations of these are placed into a collection of header files, which are part of the distribution of every C++ compiler. The implementations are placed into a collection of C++ source files, which are then precompiled into binary library files (also part of every C++ compiler distribution). C++ programmers incorporate portions of the Standard Library into their programs by making use of #include directives. In C++, a namespace is a scope; i.e., a grouping of declarations within braces. Most namespaces have names. All of the declarations of Standard Library elements have been placed within a namespace called std. Given the scope rules, names declared within a namespace are hidden from code that exists outside the namespace. Hence, we have a variety of syntaxes for making some or all of the names within a namespace visible to external code.

Computer Science Dept Va Tech May 2006

Data Structures & OO Development I

2006 McQuain & Ribbens

Typical C++ Program Organization


// single file

C++ Basics 4

For very small programs, code is often organized in a single source file; the most common convention uses the extension cpp for C++ source files.

For more interesting C++ programs, the code is typically organized into a collection of header files (extension h) and source files. In most cases, the header files contain only type declarations and function prototypes, while the cpp files contain the corresponding implementations.
// a.h // b.h // z.h

// main.cpp // a.cpp // b.cpp

. . .
// z.cpp

#include directives are used within both h and cpp files to import declarations as necessary.
Computer Science Dept Va Tech May 2006

Data Structures & OO Development I

2006 McQuain & Ribbens

The Multiple Inclusion Problem


It is possible to create some unfortunate situations:
// main.cpp #include "a.h" #include "b.h"

C++ Basics 5

Here, the preprocessor will copy the text of b.h into main.cpp twice, once due to the inclusion in a.h and once due to the explicit inclusion in main.cpp. This scenario is difficult to avoid in large projects involving many individuals or teams. However, there is a simple fix using preprocessor directives:

// a.h #include "b.h"

// b.h void foo();

// b.h #ifndef B_H #define B_H void foo(); . . .

See the CS 1704 notes on Separate Compilation for more details and an extended example.

#endif

Computer Science Dept Va Tech May 2006

Data Structures & OO Development I

2006 McQuain & Ribbens

C++ Primitive Types

C++ Basics 6

Standard C++ provides a plethora of primitive types. These store single values, and are most definitely not objects in the Java sense. In particular, there is no guarantee of automatic initialization. Integer types int unsigned int short (int) unsigned short (int) long (int) unsigned long (int) Floating-point types float double
Computer Science Dept Va Tech May 2006

Probable characteristics 32-bits 32-bits 16-bits 16-bits 32-bits 32-bits Probable characteristics 32-bit IEEE single-precision type 64-bit IEEE double-precision type

Data Structures & OO Development I

2006 McQuain & Ribbens

C++ Primitive Types


Character types char unsigned char Logical types bool Probable characteristics 1-byte, ASCII code 1-byte, unsigned integer Probable characteristics 1-byte, value either true or false

C++ Basics 7

The primitive types are all available without any inclusions from the Standard Library.

See the CS 1044 notes on C++ Fundamentals for more details and examples.

Computer Science Dept Va Tech May 2006

Data Structures & OO Development I

2006 McQuain & Ribbens

C++ Arithmetic Operators


Same syntax as Java.

C++ Basics 8

Semantics are generally the same as well, although the C++ Standard leaves the result of a number of unwise constructs undefined. For example: x = x++;

Precedence rules are the same as Java. Precedence can be forced by use of parentheses. Equality versus Identity - identity means two objects are, in fact, the same object - equality means two objects have the same value (but may or may not be identical) - in C++, operator==() means equality, not identity

Computer Science Dept Va Tech May 2006

Data Structures & OO Development I

2006 McQuain & Ribbens

C++ Input/Output Library

C++ Basics 9

The basic data type for I/O in C++ is the stream. C++ incorporates a complex hierarchy of stream classes. The most basic stream classes are the standard input/output streams: istream cin built-in input stream variable; by default hooked to keyboard

ostream cout built-in output stream variable; by default hooked to console


header file: <iostream>

C++ also provides stream types for reading from and writing to files: ifstream inFile; ofstream outFile; // input file stream object // output file stream object
header file: <fstream>

Computer Science Dept Va Tech May 2006

Data Structures & OO Development I

2006 McQuain & Ribbens

C++ Input: operator>>()

C++ Basics 10

The simplest, and most common, way to read input is to use the extraction operator (>>): int X, Y; char Z; cin >> X; cin >> Y >> Z;
Hint: the extraction operator (>>) points in the direction the data is flowing.

By default the extraction operator discards leading whitespace characters, and then parses the input stream to construct a value corresponding to the type of the target variable. It is possible for an input operation to fail, if the stream is empty or if its contents are incompatible with the target variable. In that case, the effect on the target variable is unspecified, and the input stream will set a state flag indicating it is in a fail state.

Computer Science Dept Va Tech May 2006

Data Structures & OO Development I

2006 McQuain & Ribbens

C++ Output: operator<<()

C++ Basics 11

The simplest, and most common, way to write output is to use the insertion operator (<<): int X = 42, Y = 0; char Z = 'Q'; cout << X; cout << Y << Z;
Hint: the insertion operator (<<) points in the direction the data is flowing.

The insertion operator converts the value of the source variable into ASCII text and places the resulting characters into the output stream. Formatting is entirely up to you. The code fragment above would write the following output to the console: 420Q

See the CS 1044 notes on C++ I/O for more details and examples, including formatting.

Computer Science Dept Va Tech May 2006

Data Structures & OO Development I

2006 McQuain & Ribbens

C++ Output Manipulators

C++ Basics 12

The most common way to format output in C++ is to use manipulator objects supplied by the Standard Library: endl setw(n) left right hex inserts end-of-line marker ('\n') causes the following value to be placed into a field of n columns causes the following value to be left-justified in its field causes the following value to be right-justified in its field

setfill('x') sets the fill character to be 'x' (default is a space) causes the following (numeric) value to be written in base-16 causes n digits to be shown to the right of the decimal point setprecision(n)

There are other manipulators in the Standard Library, and it is possible to implement your own, custom manipulators.

Computer Science Dept Va Tech May 2006

Data Structures & OO Development I

2006 McQuain & Ribbens

Conditionals and Loops


if ifelse switch while for dowhile

C++ Basics 13

C++ includes the same set of conditional and loop statement forms as Java:

C++ also inherits a goto statement for unconditional branching from C.

Thou shalt not goto.

Computer Science Dept Va Tech May 2006

Data Structures & OO Development I

2006 McQuain & Ribbens

Primitive Typecasts
C++ allows sensible explicit casts amongst the primitive types: double x = 6.4, y; int z = 42, w; y = (double) z; y = double(z); y = z; w = (int) x; // C/Java style cast // C++ style cast

C++ Basics 14

// implicit cast, same result as above // integer value is truncated // new-style cast

y = static_cast<double>(z);

The implicit casts are problematic; compiler may or may not issue a warning. Good style always makes typecasts explicit.

Computer Science Dept Va Tech May 2006

Data Structures & OO Development I

2006 McQuain & Ribbens

C++ typedef Statement


C++ includes a facility for declaring an alias for an existing type: typedef unsigned int uint32; typedef char PID[9];

C++ Basics 15

This does not create new types, only convenient names for specialized uses of existing types.

Computer Science Dept Va Tech May 2006

Data Structures & OO Development I

2006 McQuain & Ribbens

C++ Literals
C++ allows numeric and character-based literals: cout << "Hello, world" << endl << "pi is about " << 3.14159 << endl

C++ Basics 16

<< "and the first letter in the alphabet is " << 'A' << endl;

Computer Science Dept Va Tech May 2006

Data Structures & OO Development I

2006 McQuain & Ribbens

C++ string Type

C++ Basics 17

The C++ Standard Library includes a class string for storing and manipulating character sequences of essentially arbitrary length. string Soliloquy; Soliloquy = "To be, or not to be, that is the question."; cout << "So, then this guy says: \"" << Soliloquy << '\"' << endl;

See the CS 1044 notes on C++ I/O and on String Operations for more details and examples, including advanced input and string member functions.
Computer Science Dept Va Tech May 2006

Data Structures & OO Development I

2006 McQuain & Ribbens

Вам также может понравиться