Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Isn't this const auto& redundant?

Tags:

c++

constants

I found this code in one of Stroustrup's books:

void print_book(const vector<Entry>& book) {      for (const auto& x : book) // for "auto" see §1.5            cout << x << '\n'; } 

But the const seems redundant because x will be deduced to be a const_iterator since book is const in the parameter. Is const auto really better?

like image 315
user6417633 Avatar asked Jun 03 '16 03:06

user6417633


1 Answers

In my opinion, it looks explicit which is why it is better. So if I mean const, then I'd prefer to write it explicitly. It enhances local reasoning and thus helps others to understand the code comparatively easily — other programmers dont have to look at the declaration of book and infer that x is const as well.

like image 146
Nawaz Avatar answered Sep 20 '22 04:09

Nawaz