1

Why do some programming languages forbid returning subprocedures? Yet the language C does not?

Moreover How does C implement functions that return functions?

4

2 回答 2

2

i think that you mean function pointers? the reason that c can do that is be course c has pointers and you can declare them yourself and for example java has only a few hidden pointers

edit i found an example on the internet

#include <stdlib.h>
#include <stdio.h>

struct container
{
  struct container (* call)(int);
};

struct container look_I_return_myself(int p)
{
  struct container result;

  printf("Here's some integer someone gave me, not sure what to do with it: %d.\n", p);

  result.call = look_I_return_myself;
  return result;
}

int main(void)
{
  look_I_return_myself(3).call(4).call(5);
  return EXIT_SUCCESS;
}
于 2013-10-28T16:04:03.490 回答
2

C functions cannot return other functions; they can only return pointers to other functions. There is a difference.

One of the guiding philosophies behind the design of C is to keep it easy to implement. That's a major reason why C compilers can be found on such a wide variety of platforms. It's also a major reason why C provides so few abstractions.

Obviously, it's possible to design languages that treat function types like any other data type (Haskell, Lisp, Java, C#, etc.). The designers of C chose not to do so because the problem they were trying to solve (implementing an operating system in a high-level language) didn't really call for that level of sophistication, especially considering the limitations of the resources they were working with at the time. Remember that C is a product of the early 1970s.

于 2013-10-28T18:01:54.497 回答