[C++ Primer Reading Notes] Day 1

Scope

Chapter 1

Review

Chapter 1 is a bridf introduction to C++. It focuses on the basic knowledge of this language instead of grammar, which is mainly about the main function, the input and output stream, writing the comment, the flow of control, and the class. It shows readers how a simple C++ program works.

Notes

1. about the main function

1.1 the role of the main function plays

The operation system runs a C++ program by calling main.

The main function is the only entrance when running a C++ program.

1.2 the return type of the main function

The main function is required to have a return type of int.

For C++, returning a void is not allowed. For example:

#include <iostream>
using namespace std;

void main()  //error: '::main' must return 'int'
{
    cout<<"Hello World"<<endl;
//    return 1;
}

1.3 the return value of the main function

On most system, the value returned from main is a status indicator. A return value of 0 indicates success. A nonzero return has a meaning that is defined by the system. Ordinarily a nonzero return indicates whta kind of error occured.

Sometimes, the return value of the main function is used to instruct the next step for the system. Conventionally, 0 indicates a successful run, which tells the system that the next step can be started.

Even if we don’t write ‘return 0’ at the end of our main function, an assembly code of ‘return 0’ would be added after being complied. However, it is better to conform to this convention. Here is an example of no ‘return 0’. It shows that this program returns 0 at last.
no return
If we return 1 or other ints, the program is able to run without errors and would return the corresponding number. Here are examples of ‘return 1’ and ‘return -1’. However, if this program is used in a more complicated situation, this return value would affect later steps. Therefore it is better to conform to the convention and use ‘return 0’.
return 1
return -1

2. the relationship between type and class

A type defines both the contents of a data element and the operations that are possible on those data.

A class defines a type along with a collection of operations that are related to that type.
Every class defines a type. The type name is the same as the name of the class.

When we declare an object of a self-defined class X, we are actually declaring a variable of type X. The difference lies in whether the type is a built-in type or not.

In fact, a primary focus of the design of C++ is to make it possible to define class types that behaves as naturally as the built-in types.

That shows that the C++ program deals with a built-in type and a class type in the same way.

3. about the standard input and output

3.1 the nature of cin and cout

To handle input, we use an object of type istream named cin.
For output, we use an object of type ostream named cout.

cin and cout are actually objects of two different classes. These two classes are defined in the C++ extensive standard library.

3.2 the use of the output operator (<<)

std::cout << "Enter two numbers:" << std::endl;

The << operator takes two operands: The left-hand operand must be an ostream object; the right-hand operand is a value to print. The operator writes the given value on the given ostream. The result of the output operator is its left-hand operand. That is, the result is the ostream on which we wrote the given value.

cout is the ostream object. The function of << is to give the value “Enter two numbers:” to this object.

When defining an ostream or istream object, the system would create a buffer in the memory to temporarily store the data from output or input stream. For example, when executing the cout statement, the data is stored in the buffer until the buffer is full or encounter the endl. And then, all the data in the buffer is output to the monitor together.

The result of the first << is the object cout. This object can the left-hand operand of the second <<, which is the reason why we can use more than one consecutive << operators in one cout statement. The statement can be rewritten to:

std::cout << "Enter two numbers:" ;
std::cout << std::endl;

and

(std::cout << "Enter two numbers:") << std::endl;

3.3 the effect of endl

Writing endl has the effect of ending the current line and flushing the buffer associated with that device. Flushing the buffer ensures that all the output the program has generated so far is actually written to the output stream, rather than sitting in memory waiting to be written.

Such statement should always flush the stream. Otherwise, if the program crashes, output may be left in the buffer, leading to incorrect inferences about where the program crashed.

4. suggestion on writing the comment

One comment pair cannot appear inside another

The best way to comment a block of code is to insert single-line comments at the beginning of each line in the section we want to ignore.

Caution:
There is also one feature of comment pair that should be noticed. That is, comment pairs can be used between words in one line. For example:

// Exercise 1.8
cout << /*  "*/"  /* "/*" */;

This is a correct statement. The output is " /* ".

5. about flow of control

5.1 the relationship between while and for

This pattern–using a variable in a condition and incrementing that variable in the body–happends so often that the language defines a second statement, the for statement.

The for statement can be seen as a good replacement of while statement in some situations. Knowing about this can help us choose the right one between the two similar statements. Besides, if the loop time is known, for is better. Else, while is better.

5.2 use an istream as a condition

When we use an istream as a condition, the effect is to test the state of the stream. If the stream is valid–that is, if the stream hasn’t encountered an error–then the test succeeds. An istream becomes invalid when we hit end-of-file or enounter an invalid input, such as reading a value that is not an integer. An istream that is in an invalid state will cause the condition to yield false.

end-of-file in windows system is ‘ctrl+z’

Caution:
We should consider the situation when there is nothing to be entered when we use an istream as a condition. This can make sure when there is nothing to be entered the program can run successfully.

// Exercise 1.23
int main()
{
    Sales_item currItem, valItem;
    if (std::cin >> currItem) {  // using the if statement is better
        int cnt = 1;
        while (std::cin >> valItem) {
            if (valItem.isbn() == currItem.isbn())
                ++cnt;
            else {
                std::cout << currItem << " occurs " << cnt << " times "
                          << std::endl;
                currItem = valItem;
                cnt = 1;
            }
        }

        std::cout << currItem << " occurs " << cnt << " times " << std::endl;
    }
    return 0;
}

6. about the class

6.1 the header

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

#include <iostream>  // iostream is from the standard library
#include "Sales_item.h"  // Sales_item.h is not from the standard library

Be careful not to use the wrong format.

6.2 the call operator

We call a function using the call operator (the () operator).

item.isbn()

7. the conciseness of the code

In Exercises 1.11, although my codes have the right output, it has too many repetitions compared to other answers on the internet. I use if and while twice, which is unnecessary. It reminds me to pay attention to the conciseness.

// my version
int main()
{
    cout << "please enter two numbers: " << endl;
    int v1=0, v2=0, var=0;
    cin >> v1 >> v2;

    if(v1 < v2){
        var = v1;
        while(var <= v2){
            cout << var  << endl;
            ++var;
        }
    }

    if(v1 >= v2){
        var = v2;
        while(var <= v1){
            cout << var  << endl;
            ++var;
        }
    }
    return 1;
}
// a better version
int main()
{
    int small = 0, big = 0;
    std::cout << "please input two integers:";
    std::cin >> small >> big;

    if (small > big) {
        int tmp = small;
        small = big;
        big = tmp;
    }

    while (small <= big) {
        std::cout << small << " ";
        ++small;
    }
    std::cout << std::endl;

    return 0;
}

Word List

statement 语句
expression 表达式
operator 运算符
operand 操作数
manipulator 操作符

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值