Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What errors are saved by brevity? [closed]

Tags:

c++

"C++ Primer" (5th edition) suggests on page 149 that a brief code can be less error-prone than a longer alternative. It brings the following line of code to serve as an example:

cout << *iter++ << endl; 

It claims that the above line is less error-prone than the alternative:

cout << *iter << endl; ++iter; 

To me, even though the meaning of *iter++ is clear, this expression still requires a non-zero mental effort to parse and so the second version is more readable. So, I want to understand: what is more error-prone about the second version?

like image 859
AlwaysLearning Avatar asked Jul 01 '15 10:07

AlwaysLearning


1 Answers

I also do not agree with the author.

Usually each code snippet has a tendency to be changed in the future.

For example this statement

cout << *iter++ << endl; 

can be changed the following way

cout << *iter++ << ... << SomeFunction( *iter ) << endl; 

In this case the code will have undefined behaviour because the order of evaluation of function arguments is unspecified.

So in my opinion this code snippet

cout << *iter << endl; ++iter; 

is less error-prone.:)

Introducing side-effects in a code snippet does not make it less error-prone.

Moreover in the code snippet you showed there is no logical relation between the increment of the iterator and outputting its value.

cout << *iter++ << endl; 

So it is unclear why the iterator is incremented in this statement.

Separating this statement into two statements makes the code snippet more clear because it seems that the incrementing is related to some other parts of the code.

The brevity makes the code more expressive. But it does not mean that it necessarily makes also the code less error-prone.:)

like image 163
Vlad from Moscow Avatar answered Oct 07 '22 23:10

Vlad from Moscow