0

Does specifying size of array in parameter have any effect? For example.

void SetIDs(int IDs[22] );

versus

void SetIDs (int IDs[] );

Does it do nothing?

Thomas
  • 6,032
  • 6
  • 41
  • 79

1 Answers1

2

No, if you pass by value, an array type specifier in a parameter is always adjusted to a pointer.

void SetIDs (int IDs[22] );

void SetIDs (int IDs[] );

void SetIDs (int *IDs );

all produce the same code. Even sizeof IDs inside SetIDs will only return the size of a pointer as if IDs was declared as int *IDs.

The array size becomes relevant when you pass by reference or have a multidimensional array:

void SetIDs (int (&IDs)[22] );

This SetIDs will only accept (references to) arrays of int with size 22.

void SetIDs (int IDs[22][42] );
// equivalent to
void SetIDs (int (*IDs)[42]);

This SetIDs will accept pointers to (or an array of) an array of int with size 42.

cg909
  • 2,247
  • 19
  • 23
  • What about program safety? Would the compiler prevent you from passing an int[16] to a function using int[22]? I like having the compiler find errors for me, as it's easier and faster than for me to try and find these issues (passing wrong sized arrays) during runtime. – Thomas Matthews Sep 15 '15 at 01:25
  • No, not when passing by value. The array parameter (respectively the first dimension of a multidimensional array parameter) will behave exactly as if it was declared as a pointer, without any warnings or compiler errors. Some compilers like clang will warn e.g. if you use `sizeof` inside the function on an array parameter, but there are no warnings when calling the function with `int[16]` etc. – cg909 Sep 15 '15 at 02:22