鍍金池/ 問答/人工智能  C  C++/ 在C++中的使用比較運算符時,i++與i+1有什么區(qū)別?

在C++中的使用比較運算符時,i++與i+1有什么區(qū)別?

這是用C++寫的數(shù)組線性表的插入函數(shù),其中第二個if條件中,如果用 listSize+1 是沒有問題的,如果用 listSize++ 程序執(zhí)行是有錯誤的(非編譯錯誤)

void insert(int location, elementtype theElement)
    {
        if(location > arrayLength - 1)
            cout<<"List is full."<<endl;
        if(location > (listSize+1) || location < 1 )
            cout<<"Please enter correct value."<<endl;
        else
        {
            for(int n = listSize; n >= location; n--)
                elements[n++] = elements[n];
            elements[location] = theElement;
            listSize++;
        }
    }

i++和i+1在比較運算符中有什么區(qū)別嗎?

回答
編輯回答
墨染殤

The statement:

    if(location > listSize++ || location < 1 )
        cout<<"Please enter correct value."<<endl;

can be considered like

    if(location > listSize || location < 1 )
    {
        ++listSize;
        cout<<"Please enter correct value."<<endl;
    }
    

From the C++ Standard (5.2.6 Increment and decrement)

1 The value of a postfix ++ expression is the value of its operand. [ Note: the value obtained is a copy of the original value —end note ]...

So, it will change listSize's value(because of ++listSize;), which is not you hope to see.

2018年8月4日 09:08