0

As in topics title. When I write: void fun(int *tab){} is it the same as writing void fun(int tab[]){} ?

nullpointer
  • 245
  • 3
  • 6
  • 15

3 Answers3

3

Yes.

void fun(int *tab){}
void fun(int tab[]){}
void fun(int tab[10]){}  //whatever the size is

are all the same to the compiler. The array, with the size or not, decays to a pointer when passed as a function argument.

In practice, avoid using the last one, as it may give the implication that the size is known to the function, while actually it's not.

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
  • which makes it some of the most misleading syntactic sugar to a novice programmer... – StoryTeller - Unslander Monica Nov 02 '13 at 16:54
  • @YuHao: just one more question before I accept your answer ;) Why would I ever write the last one, I mean: `void fun(int tab[10]){}` - whats the point of doing this? What exactly does it mean? – nullpointer Nov 02 '13 at 17:08
  • 1
    @nullpointer Arrays have a size, like `int arr[10];`, just when an array is passed as function argument, it's converted to a pointer to the first element, so the size is ignored. – Yu Hao Nov 02 '13 at 17:10
2

Yes it is, and no, the second version won't let you figure out the size of the array inside the function. It still decays to a pointer. :)

Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
1

Yes it is same..Whenever you declare an array say int tab[] in your program.. and if you want to pass that array to some other function then you actually pass the base address location of that array i.e. &tab[0], which is pointed by pointer that you use as argument in function, int *tab... This actually is call by reference..

Praful Surve
  • 788
  • 1
  • 10
  • 22