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
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;
^^^