The reason behind strict rule of passing an array by pointer to a function in C++ standard.

Discussion in 'C++' started by Good Guy, Nov 19, 2010.

  1. Good Guy

    Good Guy Guest

    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.


    --
    [ See http://www.gotw.ca/resources/clcm.htm for info about ]
    [ comp.lang.c++.moderated. First time posters: Do this! ]
    Good Guy, Nov 19, 2010
    #1
    1. Advertising

  2. Good Guy <> writes:

    > 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.


    In C++ you can pass by pointer AND by reference.
    void func(const Type& obj)

    In general it doesn't make sense to pass by value things that are not
    basic types, since it involves a whole copy of the object in the stack
    of the function.

    And by the way I've never seen this thing before
    struct SampleArray{
    public:

    sure it's legal?
    Andrea Crotti, Nov 19, 2010
    #2
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.

Share This Page