Reputation: 5161
With the help of Stackoverflow, I wrote a function that outputs the sum of a vector. I want to ask:
for (auto & n : v)
? I understand code like for (auto ptr = v.begin(); ptr != v.end(); ptr++)
but 1) why we pass & n
instead of n
? Also what's the :v
?Thanks!
// version 1 that works
int sumVector(vector<int> v){
int sum_of_vec = 0;
for (auto &n: v){
sum_of_vec += n;
}
return sum_of_vec;
}
// version 2 that does not work
int sumVector(vector<int> v){
int sum_of_vec; // do not specify sum_of_vec = 0
for (auto &n: v){
sum_of_vec += n;
}
return sum_of_vec;
}
(the original question contains two parts that are not entirely covered by the possible duplicate post )
Upvotes: 0
Views: 269
Reputation: 153945
When defining an object of a built-in type without initialization it will get default initialized. However, default initialization for built-in types actually does nothing! As a result, reading the value of an uninitialized is undefined behavior! Before you can read from a corresponding object it needs to be initialized!
The reason for this somewhat odd behavior is that it is needed for two reasonably important use cases:
To support both of these use cases objects built-in types go uninitialized when nothing is specified. It is easy enough to give the objects a value: just specify a value or value initialize the object, e.g.:
int sum_of_vec{};
Upvotes: 1
Reputation: 106092
Second version is ill formed. Variable sum_of_vec
is not initialized and it will have indeterminate value. This can lead to undefined behaviour.
Upvotes: 0