猿问

请问在C++中的使用比较运算符时,i++与i+1有什么区别?

这是用C++写的数组线性表的插入函数,其中第二个if条件中,如果用 listSize+1 是没有问题的,如果用 listSize++ 程序执行是有错误的(非编译错误)

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在比较运算符中有什么区别吗?


富国沪深
浏览 1073回答 1
1回答

缥缈止盈

The statement:&nbsp;&nbsp;&nbsp;&nbsp;if(location&nbsp;>&nbsp;listSize++&nbsp;||&nbsp;location&nbsp;<&nbsp;1&nbsp;) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;cout<<"Please&nbsp;enter&nbsp;correct&nbsp;value."<<endl;can be considered like&nbsp;&nbsp;&nbsp;&nbsp;if(location&nbsp;>&nbsp;listSize&nbsp;||&nbsp;location&nbsp;<&nbsp;1&nbsp;) &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;++listSize; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;cout<<"Please&nbsp;enter&nbsp;correct&nbsp;value."<<endl; &nbsp;&nbsp;&nbsp;&nbsp;}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&nbsp;++listSize;), which is not you hope to see.
随时随地看视频慕课网APP

相关分类

数据结构
我要回答