why cant functions return arrays

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • sanjay.vasudevan@gmail.com

    why cant functions return arrays

    Why are the following declarations invalid in C?

    int f()[];
    int f()[10];

    It would be great if anyone could also explain the design decision
    for such a language restricton.

    Regards,
    Sanjay
  • Walter Roberson

    #2
    Re: why cant functions return arrays

    In article <fd8bc102-b012-4cd2-81ed-da90cde5adfa@1g 2000prg.googleg roups.com>,
    sanjay.vasudeva n@gmail.com <sanjay.vasudev an@gmail.comwro te:
    >Why are the following declarations invalid in C?
    >int f()[];
    >int f()[10];
    >It would be great if anyone could also explain the design decision
    >for such a language restricton.
    Where would the array get temporarily stored? Who would be responsible
    for freeing it?

    In a stack-based machine that mixes parameters and control, the
    information for the called routine is already on the stack by the time
    the hypothethical return array is created. As the return array could
    be of any size, the caller cannot know how much space to reserve
    "under" the stack frame for the called routine. Therefor the called
    routine would either have to somehow insert the space for the array
    "above" the stack frame for the routine itself (so that it still
    exists when the routine returns), or else the called routine would
    have to return an address of the array. If it returns an address of
    the array, the address cannot be that of an automatic variable in
    the called routine, as after the call those automatic variables
    become inaccessible. It can't use a static variable because it doesn't
    know the maximum size. So the only way to make that work would be
    to malloc() an array to store the data into, store the data, and
    return the pointer to the malloc'd area. But then what's the contract
    about who frees the array? If you require that the calling routine
    -automatically- frees the array, then you add noticable complexity
    to the language. If you require that the calling routine -explicitly-
    free the array, then you have no more expressive power than you
    already have available by making the return type a pointer and returning
    the pointer to a malloc'd area.
    --
    "History is a pile of debris" -- Laurie Anderson

    Comment

    • jacob navia

      #3
      Re: why cant functions return arrays

      Walter Roberson wrote:
      In article <fd8bc102-b012-4cd2-81ed-da90cde5adfa@1g 2000prg.googleg roups.com>,
      sanjay.vasudeva n@gmail.com <sanjay.vasudev an@gmail.comwro te:
      >
      >Why are the following declarations invalid in C?
      >
      >int f()[];
      >int f()[10];
      >
      >It would be great if anyone could also explain the design decision
      >for such a language restricton.
      >
      Where would the array get temporarily stored?
      Either in its final destination or in a temporary variable, as
      all results from functions.
      Who would be responsible
      for freeing it?
      >
      Nobody, it would be either in a result variable or in a
      temporary with automatic storage type.
      In a stack-based machine that mixes parameters and control, the
      information for the called routine is already on the stack by the time
      the hypothethical return array is created. As the return array could
      be of any size, the caller cannot know how much space to reserve
      "under" the stack frame for the called routine. Therefor the called
      routine would either have to somehow insert the space for the array
      "above" the stack frame for the routine itself (so that it still
      exists when the routine returns), or else the called routine would
      have to return an address of the array. If it returns an address of
      the array, the address cannot be that of an automatic variable in
      the called routine, as after the call those automatic variables
      become inaccessible. It can't use a static variable because it doesn't
      know the maximum size. So the only way to make that work would be
      to malloc() an array to store the data into, store the data, and
      return the pointer to the malloc'd area. But then what's the contract
      about who frees the array? If you require that the calling routine
      -automatically- frees the array, then you add noticable complexity
      to the language. If you require that the calling routine -explicitly-
      free the array, then you have no more expressive power than you
      already have available by making the return type a pointer and returning
      the pointer to a malloc'd area.

      Then, please tell me why this works?

      struct f { int array[80];};

      struct f function(void)
      {
      struct f result;
      return result;
      }

      This is the same.

      Functions can't return arrays because... an arbitrary
      decision was done ages ago that must be preserved so that
      new software remains compatible with the errors of
      the past.

      --
      jacob navia
      jacob at jacob point remcomp point fr
      logiciels/informatique

      Comment

      • jacob navia

        #4
        Re: why cant functions return arrays

        sanjay.vasudeva n@gmail.com wrote:
        Why are the following declarations invalid in C?
        >
        int f()[];
        int f()[10];
        >
        It would be great if anyone could also explain the design decision
        for such a language restricton.
        >
        Regards,
        Sanjay
        There is no reason. It is just a design mistake of the language.


        --
        jacob navia
        jacob at jacob point remcomp point fr
        logiciels/informatique

        Comment

        • Bartc

          #5
          Re: why cant functions return arrays


          "Walter Roberson" <roberson@ibd.n rc-cnrc.gc.cawrote in message
          news:fu0j1h$62s $1@canopus.cc.u manitoba.ca...
          In article
          <fd8bc102-b012-4cd2-81ed-da90cde5adfa@1g 2000prg.googleg roups.com>,
          sanjay.vasudeva n@gmail.com <sanjay.vasudev an@gmail.comwro te:
          >
          >>Why are the following declarations invalid in C?
          >
          >>int f()[];
          >>int f()[10];
          >
          >>It would be great if anyone could also explain the design decision
          >>for such a language restricton.
          >
          Where would the array get temporarily stored? Who would be responsible
          for freeing it?
          >
          This is no different to the problem of returning a struct of arbitrary (but
          known) size.
          As the return array could be of any size
          I thought C arrays were always a known fixed size, apart from VLAs.

          I think it was just decided that arrays and structs should behave
          differently (because arrays are a little special), and there is no technical
          reason why arrays cannot be passed to and returned from functions.

          --
          Bart




          Comment

          • jacob navia

            #6
            Re: why cant functions return arrays

            Bartc wrote:
            >
            I think it was just decided that arrays and structs should behave
            differently (because arrays are a little special), and there is no technical
            reason why arrays cannot be passed to and returned from functions.
            >
            Exactly. I am of the same opinion.

            --
            jacob navia
            jacob at jacob point remcomp point fr
            logiciels/informatique

            Comment

            • user923005

              #7
              Re: why cant functions return arrays

              On Apr 14, 2:25 pm, "sanjay.vasude. ..@gmail.com"
              <sanjay.vasude. ..@gmail.comwro te:
              Why are the following declarations invalid in C?
              >
              int f()[];
              int f()[10];
              >
              It would be great if anyone could also explain the design decision
              for  such a language restricton.
              I think it is basically the same idea as the electoral college:
              "Let's protect them from their own stupidity."

              Of course, you can do this:
              struct array_wrapper {
              int foo[100];
              };
              and return one of those.

              Comment

              • Ben Bacarisse

                #8
                Re: why cant functions return arrays

                "Bartc" <bc@freeuk.comw rites:
                I think it was just decided that arrays and structs should behave
                differently (because arrays are a little special), and there is no technical
                reason why arrays cannot be passed to and returned from functions.
                A little history... The situation was not so odd at first. For some
                time C restricted parameters and returned results to the basic types.
                By the time that struct passing and returning was added, it was too
                late to re-visit the secondary position held by arrays.

                --
                Ben.

                Comment

                • Richard Tobin

                  #9
                  Re: why cant functions return arrays

                  In article <fu0k3u$kvl$3@a ioe.org>, jacob navia <jacob@nospam.o rgwrote:
                  >I think it was just decided that arrays and structs should behave
                  >differently (because arrays are a little special), and there is no
                  >technical reason why arrays cannot be passed to and returned from
                  >functions.
                  >Exactly. I am of the same opinion.
                  If you were designing the language from scratch, it would be no
                  problem. But you'll have trouble fitting it in now. The natural
                  syntax is already taken. How would you pass or return an array? You
                  can't just use its name, because that syntax is already used for
                  passing or returning the address of the first element. How can you
                  declare the formal argument? Same problem.

                  -- Richard
                  --
                  :wq

                  Comment

                  • Hallvard B Furuseth

                    #10
                    Re: why cant functions return arrays

                    sanjay.vasudeva n@gmail.com writes:
                    Why are the following declarations invalid in C?
                    int f()[];
                    int f()[10];
                    Probably because of the language (mis)feature that array expressions
                    often decay to pointers to the first element of the array.

                    What would you do with that function? The 2nd variant:
                    int a[10] = f();
                    would presumably be a case of assigning the contents of an array to
                    another array, which C does not support. This won't compile either:
                    int a[10], b[10];
                    void foo() { a = b; }

                    Or if you would do this:
                    foo() { int *a; ... { ... a = f(); ... } }
                    then there is still an array-to-array assignment going on, only this
                    time to a temporary variable on the stack. However in this case it's
                    worse: The compiler may not be able to tell when the temporary becomes
                    "dead" so the space can be reused. It'd have to keep it around until
                    the function returns. This is because it created a pointer to the
                    temporary, which it won't do with other kinds of temporaries.


                    Your first version is worse still, int *a = f() would need to return
                    data of unknown size and put it on the stack.

                    --
                    Hallvard

                    Comment

                    • Default User

                      #11
                      Re: why cant functions return arrays

                      Richard Tobin wrote:
                      If you were designing the language from scratch, it would be no
                      problem. But you'll have trouble fitting it in now. The natural
                      syntax is already taken. How would you pass or return an array? You
                      can't just use its name, because that syntax is already used for
                      passing or returning the address of the first element. How can you
                      declare the formal argument? Same problem.
                      Further, arrays aren't modifiable lvalues. You can't assign the results
                      of the function to an array, which limits the usefulness to a degree.
                      You would really have start over and make arrays a first-class type.




                      Brian

                      Comment

                      • Bartc

                        #12
                        Re: why cant functions return arrays


                        "Hallvard B Furuseth" <h.b.furuseth@u sit.uio.nowrote in message
                        news:hbf.200804 15l0zd@bombur.u io.no...
                        sanjay.vasudeva n@gmail.com writes:
                        >Why are the following declarations invalid in C?
                        >int f()[];
                        >int f()[10];
                        >
                        Probably because of the language (mis)feature that array expressions
                        often decay to pointers to the first element of the array.
                        >
                        What would you do with that function? The 2nd variant:
                        int a[10] = f();
                        would presumably be a case of assigning the contents of an array to
                        another array, which C does not support. This won't compile either:
                        int a[10], b[10];
                        void foo() { a = b; }
                        >
                        Or if you would do this:
                        foo() { int *a; ... { ... a = f(); ... } }
                        then there is still an array-to-array assignment going on, only this
                        time to a temporary variable on the stack. However in this case it's
                        worse: The compiler may not be able to tell when the temporary becomes
                        "dead" so the space can be reused. It'd have to keep it around until
                        the function returns. This is because it created a pointer to the
                        temporary, which it won't do with other kinds of temporaries.
                        *a is a pointer to int. f() returns an array of int. So there is a type
                        mismatch and this should not compile, and the problem would not arise. I
                        don't think you can reasonably expect an array returned by a function to
                        'decay' to a pointer in the same way as a normal array.

                        (Creating a pointer to a value returned by a function is not a good idea
                        anyway, array or not)

                        --
                        Bart




                        Comment

                        • Dik T. Winter

                          #13
                          Re: why cant functions return arrays

                          In article <fu0k3u$kvl$3@a ioe.orgjacob@nospam.or g writes:
                          Bartc wrote:

                          I think it was just decided that arrays and structs should behave
                          differently (because arrays are a little special), and there is no technical
                          reason why arrays cannot be passed to and returned from functions.
                          >
                          Exactly. I am of the same opinion.
                          There is no technical reason. But it was already established long ago that
                          when an actual parameter was an array that what would be passed was not the
                          array but the address of the first element. Changing that to actually
                          passing the array would break a lot of code.
                          --
                          dik t. winter, cwi, kruislaan 413, 1098 sj amsterdam, nederland, +31205924131
                          home: bovenover 215, 1025 jn amsterdam, nederland; http://www.cwi.nl/~dik/

                          Comment

                          • Dik T. Winter

                            #14
                            Re: why cant functions return arrays

                            In article <4rQMj.8286$yD2 .4203@text.news .virginmedia.co m"Bartc" <bc@freeuk.comw rites:
                            ....
                            I think it was just decided that arrays and structs should behave
                            differently (because arrays are a little special), and there is no technical
                            reason why arrays cannot be passed to and returned from functions.
                            Originally functions could also not return structs (and they could not
                            be passed as parameters). Currently both are allowed for structs, but
                            none is allowed for arrayes. I think the reason is that passing an
                            array as a parameter had already an established meaning (pass the address
                            for the first element).
                            --
                            dik t. winter, cwi, kruislaan 413, 1098 sj amsterdam, nederland, +31205924131
                            home: bovenover 215, 1025 jn amsterdam, nederland; http://www.cwi.nl/~dik/

                            Comment

                            • Jack Klein

                              #15
                              Re: why cant functions return arrays

                              On Mon, 14 Apr 2008 21:57:20 GMT, "Bartc" <bc@freeuk.comw rote in
                              comp.lang.c:
                              >
                              "Walter Roberson" <roberson@ibd.n rc-cnrc.gc.cawrote in message
                              news:fu0j1h$62s $1@canopus.cc.u manitoba.ca...
                              In article
                              <fd8bc102-b012-4cd2-81ed-da90cde5adfa@1g 2000prg.googleg roups.com>,
                              sanjay.vasudeva n@gmail.com <sanjay.vasudev an@gmail.comwro te:
                              >Why are the following declarations invalid in C?
                              >int f()[];
                              >
                              >int f()[10];
                              >It would be great if anyone could also explain the design decision
                              >for such a language restricton.
                              Where would the array get temporarily stored? Who would be responsible
                              for freeing it?
                              >
                              This is no different to the problem of returning a struct of arbitrary (but
                              known) size.
                              This is true, but the in the early days of C one could not pass or
                              return structures by value, either. They were mentioned as a feature
                              that was coming, but not yet available on all implementations , in the
                              original K&R.

                              C was originally developed to create executables for extremely memory
                              constrained platforms. It is still widely used for that purpose in
                              embedded systems, the major use of C today.

                              Once you added the ability to pass and return structures by value, you
                              have the ability to define your arrays inside of structures and do
                              this when you want.

                              Since you have the ability to do it with structs, you do not risk
                              serious code breakage that could have occurred due to the (IMO
                              unfortunate) conversion of array arguments to pointer arguments in
                              function definitions (also declarations and, much later, prototypes).

                              Code like this:

                              int func1(ap)
                              int *ap;

                              ....would continue to work as before, and:

                              int func1(ap)
                              int ap[];

                              ....would continue to work as before, but:

                              int func1(ap)
                              int ap[10];

                              ....might suddenly work very differently. Especially in the absence of
                              prototypes.

                              Adding pass and return of structs by value did not break existing
                              code. Passing arrays by value most certainly would have.

                              --
                              Jack Klein
                              Home: http://JK-Technology.Com
                              FAQs for
                              comp.lang.c http://c-faq.com/
                              comp.lang.c++ http://www.parashift.com/c++-faq-lite/
                              alt.comp.lang.l earn.c-c++

                              Comment

                              Working...