0

when i put

for(int &i:arr){
    i+=2;
}

in a function outside the main function, It shows error:

solution.cpp: In function 'void fun(int*, int)':

solution.cpp:8:13: error: 'begin' was not declared in this scope; did 
you mean 'std::begin'?

  |  for(int &i:arr){

  |             ^~~

but I put in main function it works perfectly fine.

I am not able to find the reason behind this. Please Help & Thanks in Advance.

This one is Showing Error

#include <algorithm>
#include <iostream>
#include <vector>

using namespace std;

void fun(int arr[], int n){
    for(int &i:arr){
        i+=2;
    }
}
int main() {
    int arr[]={1,2,3,4,5,6};
    fun(arr,6);
    
    for(int i:arr){
        cout<<i<<" ";
    }

    return 0;
}

& This One is working fine

#include <algorithm>
#include <iostream>
#include <vector>

using namespace std;


int main() {
    int arr[]={1,2,3,4,5,6};
    

    for(int &i:arr){
        i+=2;
    }

    for(int i:arr){
        cout<<i<<" ";
    }

    return 0;
}
  • In a function parameter, `int arr[]` is the same as `int *arr`, and a `range-for` loop can't enumerate a pointer. Since you are passing the array in as a pointer, and are passing in the array size as another parameter, you can use a normal `for` loop Instead, eg: `void fun(int arr[], int n){ for(int i = 0; i < n; ++i){ arr[i] += 2; } }` – Remy Lebeau Apr 16 '22 at 03:26

0 Answers0