简体   繁体   中英

default parameters in function call in C

Lets say in a file I have some code in two files part of the same project

file1.c
int func1(int a, int b, int c, bool d)
{
        /* function body */
}

file2.c
extern func1(int a, int b, int c);

/* function call */
func1(runtime1, runtime2, runtime3);

What would be value bool d takes when being called from file2.c? I know this is really bad practice, but I am maintaining old code and somebody did this, I just want to know the default parameter or if it is implementation dependent. Please note also, that bool in this example is a typedef of the software, since this specific project does not support C99. Thank you.!

The value is not just implementation-dependent; the entire behavior of the program is undefined. If you'd put the declaration for func1 in a header instead of in file2.c and you'd include that header in file1.c , as is good C practice, the compiler would refuse to compile this.

In practice, you'll likely observe d as having some arbitrary, unpredictable value, though your program might also crash mysteriously.

The value would be undefined. When calling func1, its parameters go on the stack. If you call it with 1 parameter less, the stack will be sizeof(bool) bytes short of what the process expects. This will not crash your program as your stack and your heap are "facing", but if you try to access to d , you will access to whatever value is there on the stack -> rubbish.

This program is undefined behavior . As the program is undefined behavior the compiler has the right to refuse to compile it.

(C99, 6.2.7p2) "All declarations that refer to the same object or function shall have compatible type; otherwise, the behavior is undefined."

The two function declarations in your program are not compatible; they don't have the same number of parameters.

(C99, 6.7.5.3p15) "For two function types to be compatible, both shall specify compatible return types. Moreover, the parameter type lists, if both are present, shall agree in the number of parameters and in use of the ellipsis terminator; corresponding parameters shall have compatible types."

It can be any value, garbage from the stack I believe if you call the method that way.

The program will have undefined behavior because you really do not know the value of the bool parameter. It may also crash during the execution.

Hope it helps.

It's undefined behavior - it may have garbage value, and it may also crash, depend on the calling convention of your compiler and OS.

Edit: The other arguments may also be mixed, if they are been pushed from left to right.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM