No defined type of a function parameter defaults to int? Am I insane?

前端 未结 3 991
情深已故
情深已故 2020-11-30 12:46

For some odd reason I was copying an example in another language of which does not use types, and forgot to add one in to a function definition parameter, and it worked.

相关标签:
3条回答
  • 2020-11-30 13:08

    afaik this is called argument promotion. i do not recall the exact rules, but it comes down to the compiler being allowed to use int for arguments when he (she?) doesn't know the function prototype yet.

    0 讨论(0)
  • 2020-11-30 13:21

    @Erik's answer is correct, but (IMO) could be misunderstood rather easily.

    What you have is a K&R style definition, that's entirely true. Since int is considered the default type, if you have something like: foo(n) { }, it means the return type and the type of n are both int by default.

    C99 (mostly) removes the "default int" rule, but does not entirely remove K&R style definitions. That means the definition above is no longer allowed; to define foo with the same types as above, you could still use:

    int foo(n)
    int n;
    {
    }
    

    I.e., the K&R style definition is still allowed, but you do have to specify the return type and the parameter type, even if the type is int.

    This style of function definition is, however, obsolescent (per §6.11.7). It's really only still allowed for the sake of ancient (pre-standard) code. You don't want to write new code this way, even though it's technically still allowed. For new code, you clearly want to use a prototype-style definition:

    int foo(int n) {}
    

    For those who care about such things, the K&R style definition is still used in some new code though. Its terser style can be useful (using the term loosely) in code-golf.

    As long as we're at it: @stijn's answer is sort of correct as well. In particular when a function is defined this way (I.e., K&R style), all arguments are subject to default promotions. That means if you pass an integer type smaller than int, it'll be promoted to int before being passed, and if you pass a float, it'll be promoted to double.

    0 讨论(0)
  • 2020-11-30 13:29

    K&R-style function declaration:

    void foo(n) 
        int n; 
    {
    
    }
    

    If type isn't specified, it defaults to int. This is valid in C89, not C99

    0 讨论(0)
提交回复
热议问题