首页 > 代码库 > [C++] Variables and Basic Types

[C++] Variables and Basic Types

 Getting Started

compile C++ program source

$ g++ -o prog grog1.cc

run C++ program

$ ./prog

 

The library, iostream, define four IO object: cin, cout, cerr, clog.

    std::cout << "hello world" << std::endl;

The result of the output operator << is the left-hand operand.

the :: in the std::out, is the scope operator.

 

The while statement is used as a loop.

The for statement is the abbrevious code for the an pattarn, in which using a variable in a condition and incresing the variable in the body.

 

The End-of-File from the keyboard in mac OSX is control-d.

 

It is good practice to correct errors in the sequnce they are reported. 

 

Once you have chosen a code style, use it consistently.

 

#include <iostream>#include "myUtility.h"

Header from the standard library are enclosed in angle bracket(<>). Those that are not part of library are enclosed in double quotes("").

 

Variables and Basic Types

C++, like C, is designed to let programs get close to the hardware when neccesary.

If you need a tiny integral, explicity either signed char or unsigned char, rather than just char.

Use double for floating-point computation. float usually does not have enough precision.

 

If we assign an out-of-range value to an object of unsigned type, the result is the remainder of the value modulo the number of values the target type can hold.

If we assign an out-of-range value to an object of signed type. the result is undefined.

 

Regardless of whether one or both operands are unsigned if we substract a value from an unsigned, we must ensure  that the result cannot be negative.

    unsigned u1 = 42, u2 = 10;    std::cout << u2 - u1 << std::endl;    // ok; but the result would wrap around

Expression that mix signed and unsinged values can yield surprising results, when the signed value is negative.

 

Uninitialized object of built-in type defined outside a function body have undefined value.

Object of class type that we do not explictily initialize have a value that is defined by the class.

 

Unitialized variables causes Run-time problems. We recommend initialize every object of bulit-in type.

 

Naming convertions are most useful when followed consistently.

 

A scope is part of the program in which a name has aparticular meaning. Most scope in C++ are delimited by curly braces.

 

Define Variables where you first use them.

 

#include <iosteam>int reused = 42;int main(){    std::out << reused << std::endl;    int reused = 0;    std::out << reused << std::endl;    std::out << ::reused << std::endl;    return 0;  }

The global scope has no name. When the scope operator(::) has an empty left-hand side, it is a request to fetch the name on the right-hand side from the global scope.

Avoid to define the same name variable in inner/outter scopes.

 

Reference

When we use the term reference, we mean "lvalue reference". 

A reference defines an alternative name for an object. There is no way to rebind a reference to refer to a different object. A reference must be initialized.

Reference is an aliase. A reference is not an object. Instead, a references is just another nmae for an already existing object. After a reference has been defined, all operation on the reference are actually operations on the object to which the reference is bind.

    int ival = 1024;    int &refVal = ival;    // refVal is an aliase of ival    refVal = 2;            // assign 2 to the object to which refVal refers to, ival    int ii = refVal;       // same as ii = ival    int & refVal3 = refVal;    // ok; refVal is bind to the object to which refVal is bound, i.e. to ival.

Because reference are not object, we may not define a reference to a reference.

The type of a reference and the object to which the reference refers must match exactly. A reference must be boud only to an object, not a literal.

    int &refVal4 = 10;    // error: initializer must be an object    double dval = 3.14;    int &refVal5 = dval;    // eror: initilizer must be an int object.

 

Pointer

Like reference, pointers are used for indirect access to other objects;

Unlike a reference, a pointer is an object in its own right, and can be assigned and copied. A single pointer can point to serval different object over its lifetime.

Pointer are often hard to understand. Debuging problem due to pointer errors bedevail even experienced programmers.

A pointer hold the address of another object, we get the address of an object by using the address-of operator(&).

    int ival = 42;    int *p = &ival;    // p holds the address of ival; p is a pointer of ival

Because reference are not objects, they do not have address. Hence, we may not define a pointer to a reference.

The type of pointer and the object to which it points must match.

    int ival = 42;    int *p = &ival;    std::cout << *p;    // * yield the object to which p points; print 42    *p = 0;             // * yiled the object; we assign a new value to ival through p    std::cout << *p;

When we assign to *p, we are assigning to the object to which p points.

 

Dereferencing a point yileds the object to whch the pointer points.

 

Some symbols have multiple meaning

some symbols, such as & and *, are used as both an operator in an expression and as part of declaration.

    int i = 42;    int &r = i;    // & follows a type and is part of a declaration; r is a reference    int *p;        // * follows a type and is part of a declaration; p is a pointer    p = &i;        // & is used in an expression as the address-of operator    *p = i;        // * is used in an expression as the dereference operator.    int &r2 = *p   // & is part of the declaration; * is the dereference operator.

In delcarations, & and * are used to form compound types. In expressions, these same symbols are used to declare an operator. Because the same symbol is used with very differenct meaning, it can be helpful to ignore appearces and think of them as if they are different symbols

 

Older program sometimes use a prepocessor variable name NULL, which the cstdlib header define as 0.

The preprocess is a program that runs before the compiler.

Preprocessor variable are managed by the preprocessor, and are not part of the std namespace. As a result, we refer to them directly without the std:: prefix.

When we use a preprocessor variable, the preprocessor automatically replaces the variable by its value.

 

Unintialized pointer are a common source of run-time errors.

Intialize All Pointers. If possible, define a pointer only after the object to which it should point has been defined.

If there is no object to bind to a pointer, then initialize the pointer to nullprt or zero.

 

Assignment and Pointers

    int ival = 42, ival2 = 53;    int *pi =ival2;    pi = &ival;    // value in pi is changed; pi not point to ival2

We assign a new values to pi, which changes the address that pi holds.

    *p = 0;    // value in ival is changed. pi is unchanged

 

void* pointer

The type void* is a special pointer type that can hold the address of any object. The type of the object is unknown.

We cannot use a void* to operate on the object it address -- we don‘t know that object‘s type, and the type detemine what operations we can perform on the object. Generally, we use a void* ponter to deal with memory as memory.

 

Understanding compound Type Declaration

Define multiple variables.

It is a common misconception to think that the type modifier(& or *) applied to all the variable defined in a single statement.

    int* p;     // legal, but might be misleading    int* p1, p2;     // p1 is a pointer to int; p2 is an int    int *p3, *p4;    // both p3, p4 are pointers to int

 

Reference to Pointers

    int i = 42;    int *p;        // p is a pointer to int    int *&r = p;    // r is a reference to the pointer p    r = &i;    // r refers to pointer p, assigning &i to r makes p points to i    *r = 0;    // dereference r yield i, the object to which p points; change i to 0

It can be easier to understand complicated pointer or reference declaration if you read them from right to left.  

    int *&r = p

& indicates r is an reference. The next symbols ‘*‘, says that the type r refers to is a pointer type.  Finally, the base type of the declaration says that r is a reference to a pointer to an int.

 

Qualifier

By default, const objects are local to a file.

To define a single instance of a const variable across multiple files. we use the keyword extern on both its definition and declarations.

// file.cc, define and initializes a const that is accessible to other files    extern const int bufSize = fun();// file.h    extern const int bufSize;    // same bufSize as defined in file.cc

 

A Reference to const may refer to an object that is not const.

Pointers and Const

Like a reference to const, a pointer to const may not used to change the object to which the pointer points. Defining a pointer as a pointer to const affect only what we can do with the pointer.

Const Pointers

Unlike references, pointer are objects. We can have apointer that is const. Like any other const object, a const pointer must be initialized, and once initilized, it‘s value(i.e. the address that it holds) may not be changed.

We indicate that the pointer is const by putting the const after the *

    int errNumb = 0;    int *const curErr = &errNumb;    // curErr will always points to errNumb    const double pi = 3.14;    const double * const pip = &pi    // pip is a const pointer to a const object

The easiest way to understand these declaration is to read them from right to left.

 

Top-level const

We use the term top-level const to indicate that the pointer itself is a const. we use the term low-level const to indicate the const object to which an pointer points.

    const int * const p3 = p2;    // right-most const is top-level. left-most const is low-level

When we copy an object, top-level const are ignored, while low-level is never ignored.

 

Dealing with Types

Type aliases

Traditionally

    typedef double wages;    // wages is a synonym for double    typedef wages base, *p;    // base is synonym for double, p for double*

New aliase declaration

    Using SI = Sales_item;    // SI is a synonym for Sale_item

Usage

    wages hourly, weekly;    // same as double hourly, weekly    SI item;                 // same as Sale_item item

Pointer, Const, and Type Aliase

    typedef char * pstring;      const pstring cstr = 0;    // cstr is a constant pointer to char

It can be tempting, albit incorrect, to interpret a declaration that use a type aliase by conceptually replacing the aliase with its corresponding type:

    const char * cstr = 0;    // wrong interpretion of const pstring cstr

When we use pstring in a declaration, the base type of the deration is a pointer type. When we rewrite the declaration using char *, the base type is const char. This rewrite declarate cstr as a pointer to const char rather than as a const pointer to char.

 

auto type

    auto item = val1 + val2;

auto tell the compiler to deduce the type from the initilizers.

When we define serval variables in the same statement. it is important to remember that a reference or pointer is part of particular declarator and not part of the base type for the declaration.

 

Defining our own Data structure

Whenever a header is updated, the source files that use that header must be recompiled to ge the new or changed declarations.

Header Gards: #ifndef, #ifdef, #endif

Headers shold have gards, even if they aren‘t(yet) included by another header.

To avoid name clashed with other entities in our program, preprocessor variables usually are written in all uppercase.

 

Reference:

C++ Primer, Fifth Edition

[C++] Variables and Basic Types