Search code examples
c++c++11auto

Adding the two integers but one declared as an "int" and other as "auto"?


I am trying to find the sum of all the elements in an array, and declaring my initial accumulator variable sum as 0 using auto.

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;

int main(){
    int n;
    auto sum {0};
    cin >> n;
    vector<int> arr(n);
    for(int arr_i = 0;arr_i < n;arr_i++){
        cin >> arr[arr_i];
        sum=sum+arr[arr_i];
     }
     cout<<sum;
     return 0;
}

It is giving me a compilation error. I want to know what is wrong with this.

error: no match for 'operator+' in 'sum + arr.std::vector<_Tp, _Alloc>::operator[] >(((std::vector::size_type)arr_i))'|

I'm using code blocks with gcc compiler and yes C++ 11 is enabled.


Solution

  • In C++11, when you use

    auto sum {0};
    

    thensum is of type std::initializer_list<int> and contains one element, 0. This is because the {0} is a braced initialization list.

    Using = 0; or (0) should work properly for your code, e.g:

    auto sum = 0;
    auto sum(0);
    

    EDIT: According to the comments this was NOT what programmers usually expected, hence it is bound to change in C++17 with the N3922 proposal, which is already implemented in newer versions of GCC and Clang, with even for -std=c++11 and -std=c++14 per the request of the C++ committee.