Search code examples
c++arrayspass-by-referencereturn-typecompile-time

Explain syntax for returning array by reference from a function


The syntax of function in C++ is:

return_type function_name(parameter1, parameter2, ...)
{
    // function body
}

I have some doubts regarding "returning reference of an array from a function":

  1. Return type is specified first then function name but to return reference of an array it is written as:

    // for array of size 10
    int (&f())[10] {
       return global;
    }        
    

    why?

  2. Can it be written as below:

    // return type followed by function name
    int&[10] f(){
       return global;
    }
    

    or something similar(without typedef)?

  3. I couldn't understand typedef usage when using it like:

    typedef int array_t[10];
    array_t& f() {
       return global;
    }
    

    how will the above code be simplified? and will the simplified code look like the code in point 1?


Solution

    1. why?

    Because Dennis Ritchie designed it to be so in C, and because C++ was designed to be compatible with C.

    There weren't references in C of course, but references follow the same syntax rules as pointers do, which were inherited from C.

    The main confusion however doesn't seem to be about where the reference puncutator goes, but rather about the array syntax. The array size simply always goes to the right side of the name. This same pattern is also true for variables:

    int arr[size];
    |   |  |
    |   |  size
    |   name
    element type
    
    int (&arr_ref)[size];
    |     |       |
    |     |       size
    |     name
    element type
    
    int (&f())[10]
    |     |   |
    |     |   size
    |     name
    element type
    

    Function declaration is different only in the regard that it has the parameter list. Which is always immediately after the name. And because it is immediately after the name, it is consequently before the array size.

    1. Can it be written as below:

    No. That is ill-formed in C++.

    1. I couldn't understand typedef usage when using it like:

    typedef is simply an alias; a different name for the type.

    how will the this code be simplified?

    The code in 3. is optimally simple. Personally, I prefer the using syntax for type aliases instead of typedef:

    using array_t = int[10];
    

    Another option is to use trailing return type, although it whether this is more or less simple is subjective:

    auto f() -> int(&)[10] {
    

    and will it look like the code in point 1?

    The decaration looks different, but it declares the same function.