Order of incrementing and dereferencing pointer in C++

前端 未结 3 780
既然无缘
既然无缘 2021-01-14 10:06

I tutor students in C++, and recently came across a problem involving pointer arithmetic with array names. The main thing I\'m confused about is the statement



        
3条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-14 10:21

    This expression

    T min_value = *begin++; 
    

    can be imagined the following way

    auto temp = begin;
    T min_value = *temp;
    ++begin;
    

    According to 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 ] ...The value computation of the ++ expression is sequenced before the modification of the operand object.

    In general case the function definitions are wrong because the range specified by begin and end can be empty and begin can point beyond a valid range. In this case you may neither increase begin nor dereference it.

    So it would be more correctly to write for example the following way

    T * min( T* begin, T* end ) 
    {
        T *min_value = begin;
    
        if ( begin != end )
        {
            while( ++begin != end )
            { 
                if( *begin < *min_value ) min_value = begin; 
            } 
        }
    
        return min_value; 
    } 
    

    In this case the call of the function will look like

    cout << "min of arr[] is : " << *min(arr, arr + 5) << endl;
                                   ^^^
    

提交回复
热议问题