0

In C++ the only way to pass an array to a function is by pointer, considering following functions:

void someFunc(sample input[7]){
 //whatever
}
void someFunc(sample input[]){
 //whatever
}
void someFunc(sample (& input)[7]){
 //whatever
}

All above function parameters are identical with following function parameter when the function is not inlined:

void someFunc(sample * input){
 //whatever
}

Now to pass the array with value we have to put it in a structure like below:

struct SampleArray{
 public:
  sample sampleArray[7];
};

Now I'd like to know if anyone knows the reason behind this design in C++ standard that makes passing pure arrays by value impossible by any syntax and forces to use structs.

Pooria
  • 2,017
  • 1
  • 19
  • 37
  • 1
    Probably not the only reason - may not even be the main reason - but if the size of `sample` was huge, e.g., 1 MB, passing an array of 7 `sample` objects by value would not be efficient and would blow the default stack. – Matt Davis Nov 18 '10 at 18:51

3 Answers3

2

Backward compatibility reasons. C++ had no choice but to inherit this behavior from C.

fredoverflow
  • 256,549
  • 94
  • 388
  • 662
1

This answer to the earlier similar question addresses the reasons why such behavior was introduced in C (or, more specifically, why arrays and arrays within structs are handled differently by the language).

C++ adopted that part of C, but added the ability to pass arrays by reference (note that your third version of someFunc passes the array by reference, and is not equivalent to using a pointer to its first element). In addition, C++ includes various container types that can be passed by value (recently including std::array)

Community
  • 1
  • 1
Cubbi
  • 46,567
  • 13
  • 103
  • 169
0

Probably as a function of its C ancestry. Arrays being just pointers to memory it'd be kind of hard for that to be done transparently without generating extra code by the compiler. Also it's trivial to implement a container class that does lazy copy on write, which will perform better.

Novikov
  • 4,399
  • 3
  • 28
  • 36