jeudi 2 mai 2019

Array as argument to function

Here in f() I accept array to be of maximum size 4 but it still runs fine when I pass an array of size greater than 4(here 10), I know arrays in c++ are passed as pointers by default but than when is this method of passing array useful?

#include<iostream>

using namespace std;

void f(int a[4]){
    for(int i  = 0;i < 3;i++){
        a[i] += 10;
    }
}

int main(){
    int a[10];
    for(int i = 0;i < 10;i++)
        a[i] = i;
    f(a);
    for(int i =0 ;i < 10;i++){
        cout<<a[i]<<" ";
    }
    cout<<"\n";
    return 0;
}

output: 10 11 12 3 4 5 6 7 8 9

Aucun commentaire:

Enregistrer un commentaire