Why do we specify arrays size as a parameter when passing to function in C++?

  • A+
Category:Languages

I searched this question, most of them says the same thing. Since we only pass the arrays address in a function, compiler can not know the arrays size by looking at the address, they say. I tried to test this by using this code, and both functions gave the same results. So, how does specifying the arrays size as a function parameter help me in a practical way?. In which conditions does specifying the size help us?.

class ArrayTest {     public:      void say(int ar[])      {          cout<<ar[1]<<endl;          cout<<ar[7]<<endl;      }        void say(int ar[],int sizeAn)      {          cout<<ar[1]<<endl;          cout<<ar[7]<<endl;      }  };  int main() {     ArrayTest test;    int anAr[5] = {1,2,3,4,5};    test.say(anAr);    test.say(anAr,5);     return 0;  } 

 


This is about you as a programmer having the chance to boundary check, not whether the compiler can do it.

Just try to print out all the elements in the array, with the size:

 void say(int ar[],int sizeAn)  {      for(int i=0; i< sizeAn; ++i)          cout<<ar[i]<<endl;  } 

now without the size:

 void say(int ar[])  {      for(int i=0; i< /*HOW DO I KNOW NOW?*/; ++i)          cout<<ar[i]<<endl;  } 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: