yuqli
yuqli

Reputation: 5161

C++ how to understand (auto & n : v)?

With the help of Stackoverflow, I wrote a function that outputs the sum of a vector. I want to ask:

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

Answers (2)

Dietmar K&#252;hl
Dietmar K&#252;hl

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:

  • When allocating [huge] arrays of objects it is common the they’ll receive a non-default value from some source and value initializing them would unnecessarily waste time.
  • When constructing an object into a region of memory mapped I/O it may not be possible to write to the corresponding location at all or it could have adverse effects.

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

haccks
haccks

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

Related Questions