Getting Started

compile C++ program source

  1. $ g++ -o prog grog1.cc

run C++ program

  1. $ ./prog

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

  1. 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.

  1. #include <iostream>
  2. #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.

  1. unsigned u1 = , u2 = ;
  2. 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.

  1. #include <iosteam>
  2. int reused = ;
  3. int main(){
  4. std::out << reused << std::endl;
  5. int reused = ;
  6. std::out << reused << std::endl;
  7. std::out << ::reused << std::endl;
  8. return ;
  9. }

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.

  1. int ival = ;
  2. int &refVal = ival; // refVal is an aliase of ival
  3. refVal = ; // assign 2 to the object to which refVal refers to, ival
  4. int ii = refVal; // same as ii = ival
  5. 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.

  1. int &refVal4 = ; // error: initializer must be an object
  2. double dval = 3.14;
  3. 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(&).

  1. int ival = ;
  2. 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.

  1. int ival = ;
  2. int *p = &ival;
  3. std::cout << *p; // * yield the object to which p points; print 42
  4. *p = ; // * yiled the object; we assign a new value to ival through p
  5. 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.

  1. int i = ;
  2. int &r = i; // & follows a type and is part of a declaration; r is a reference
  3. int *p; // * follows a type and is part of a declaration; p is a pointer
  4. p = &i; // & is used in an expression as the address-of operator
  5. *p = i; // * is used in an expression as the dereference operator.
  6. 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

  1. int ival = , ival2 = ;
  2. int *pi =ival2;
  3. 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.

  1. *p = ; // 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.

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

Reference to Pointers

  1. int i = ;
  2. int *p; // p is a pointer to int
  3. int *&r = p; // r is a reference to the pointer p
  4. r = &i; // r refers to pointer p, assigning &i to r makes p points to i
  5. *r = ; // 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.

  1. 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.

  1. // file.cc, define and initializes a const that is accessible to other files
  2. extern const int bufSize = fun();
  3. // file.h
  4. 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 *

  1. int errNumb = ;
  2. int *const curErr = &errNumb; // curErr will always points to errNumb
  3. const double pi = 3.14;
  4. 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.

  1. 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

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

New aliase declaration

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

Usage

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

Pointer, Const, and Type Aliase

  1. typedef char * pstring;
  2. const pstring cstr = ; // 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:

  1. const char * cstr = ; // 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

  1. 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的更多相关文章

  1. C++ Variables and Basic Types Notes

    1. Type conversion: If we assign an out-of-range value to an object of unsigned type, the result is ...

  2. C++Primer 5th Chap2 Variables and basic Types

    wchar_t,char16_t,char32_t用于拓展字符集 char和signed char并不一样,由编译器决定类型char表现上述两种中的哪一种 一般long的大小和int无二,如果超过in ...

  3. TypeScript学习指南第一章--基础数据类型(Basic Types)

    基础数据类型(Basic Types) 为了搭建应用程序,我们需要使用一些基础数据类型比如:numbers,strings,structures,boolean等等. 在TypeScript中除了Ja ...

  4. A Tour of Go Basic types

    Go's basic types are bool string int int8 int16 int32 int64 uint uint8 uint16 uint32 uint64 uintptr ...

  5. 编译器重复定义错误:error C2371: 'SIZE' : redefinition; different basic types

    我们常常会定义自己工程用的数据类型,可能会与Windows的基本数据类型冲突. vs会报重复定义错误:error C2371: 'SIZE' : redefinition; different bas ...

  6. QML学习【一】Basic Types

      QML入门教程(1) QML是什么? QML是一种描述性的脚本语言,文件格式以.qml结尾.语法格式非常像CSS(参考后文具体例子),但又支持javacript形式的编程控制.它结合了QtDesi ...

  7. [GraphQL] Use GraphQL's Object Type for Basic Types

    We can create the most basic components of our GraphQL Schema using GraphQL's Object Types. These ty ...

  8. Kotlin Reference (四) Basic Types

    most from reference 基本类型 在kotlin中,一切都是对象,我们可以在任何变量上调用成员函数和属性.一些类型可以具有特殊的内部表示:例如,数字.字符和布尔值都可以在运行时被表示为 ...

  9. Go xmas2020 学习笔记 00-03、Basic Types

    00-02-Hello Example. 目录结构. 不一样的Hello World. 巧妙的单元测试. 传入os.Args切片. go mod init. 03-Basic Types. 变量类型与 ...

随机推荐

  1. ios之coredata(一)

    下面开始学习一下CoreData. Core Data不是一个关系型数据库,也不是关系型数据库管理系统(RDBMS).Core Data 为数据变更管理.对象存储.对象读取恢复的功能提供了支持. 它可 ...

  2. mysql对查出来的值,在sql里面拼接我们想要拼接的内容

    MySQL中concat函数使用方法:CONCAT(str1,str2,…) 返回结果为连接参数产生的字符串.如有任何一个参数为NULL ,则返回值为 NULL. 注意:如果所有参数均为非二进制字符串 ...

  3. 「PHP」策略模式

    引言   所属:行为型模式,常用设计模式之一     学习资料: <大话设计模式>程杰   模式概述   分享一篇关于策略模式讲的很好的文章,大家可以参考一下:https://www.cn ...

  4. [Doctrine Migrations] 数据库迁移组件的深入解析一:安装与使用

    场景分析 团队开发中,每个开发人员对于数据库都修改都必须手动记录,上线时需要人工整理,运维成本极高.而且在多个开发者之间数据结构同步也是很大的问题.Doctrine Migrations组件把数据库变 ...

  5. [原创]用python检测LVS real server状态实现HTTP高可用

    import httplib import os import time def check_http(i): try: conn=httplib.HTTPConnection(i, 80, time ...

  6. TensorFlow之tf.nn.dropout():防止模型训练过程中的过拟合问题

    一:适用范围: tf.nn.dropout是TensorFlow里面为了防止或减轻过拟合而使用的函数,它一般用在全连接层 二:原理: dropout就是在不同的训练过程中随机扔掉一部分神经元.也就是让 ...

  7. Git中分支merge和rebase的适用场景及区别

    Git merge是用来合并两个分支的. git merge b      # 将b分支合并到当前分支 同样 git rebase b,也是把 b分支合并到当前分支 原理 如下: 假设你现在基于远程分 ...

  8. 北京Uber优步司机奖励政策(4月4日)

    滴快车单单2.5倍,注册地址:http://www.udache.com/ 如何注册Uber司机(全国版最新最详细注册流程)/月入2万/不用抢单:http://www.cnblogs.com/mfry ...

  9. 人脸检测库libfacedetection介绍

    libfacedetection是于仕琪老师放到GitHub上的二进制库,没有源码,它的License是MIT,可以商用.目前只提供了windows 32和64位的release动态库,主页为http ...

  10. elasticsearch增删改查操作

    目录 1. 插入数据 2. 更改数据 3. 删除数据 4. 检索文档 1. 插入数据 关于下面的代码如何使用,可以借助于kibana的console,浏览器打开地址: http://xxx.xxx.x ...