Home > Net >  Why is it not possible to use implicitly typed function arguments with explicitly typed function arg
Why is it not possible to use implicitly typed function arguments with explicitly typed function arg

Time:01-05

If i were to compile the below code:

// x is implicitly typed as int
void foo(x, char y) {
    return;
}

a syntax error would occur (expected identifier), but im not sure why the compiler can't handle this syntax.

however if i do:

void foo(int x, char y) {
    return;
}

it compiles successfully.

So why can't the compiler handle such syntax? Im no expert at C so im not sure if this is a silly question or not.

CodePudding user response:

Implicit argument types, or more accurately a function definition with an identifier list, was part of the original K&R design of C. In those days, you could either have a definition like this:

int foo(x, y) 
{
    return 0;
}

In which case all parameters default to type int, or a set of declarations before the body:

int foo(x, y) 
   int x;
   char *y;
{
    return 0;
}

To specify the types of the arguments. In neither case were the types of the parameters known to the caller.

Specifying the types directly in the definition was added to the language later, which also added the ability to specify the types of a function's arguments in a declaration, allowing callers to know the types of the parameters.

So there's wasn't much reason to have a hybrid of the two, as one was made to improve on the other.

CodePudding user response:

This problem is not specific to the C language. With the definition of the function alone, it is not possible for a compiler to guess the type of the parameter x. And even if there is some call to foo with an int as first argument, it is not enough to determine that the type of the x parameter must be int. There might be other calls to foo that will be compiled later.

In some languages, like OCaml, the compiler will be able to produce a generic function with a first parameter of type 'a, where `'a' is a type variable, meaning that the function can be given a value of any type as first argument.

But this comes with a cost for making the compiled code generic. In C, the compiler need to know the memory size to allocate for the first parameter in order to produce the correct assembly code.

  • Related