问题
An interview question arise a strong confusion in my mind i.e Lets see this program
#include "stdio.h"
int main()
{
static int a=25;
void cdecl conv1();
void pascal conv2();
conv1(a);
conv2(a);
return 0;
}
void cdecl conv1(int a,int b)
{
printf("%d%d", a, b);
}
void pascal conv2(int a,int b)
{
printf("\n%d%d", a, b);
}
Output is
25 0
0 25
But why? And how?
Can you briefly explain to me because I don't understand this program mentioned in UGC book.
Please help me to understand this concept more finely, so that I can better prepare for my interview.
Thanks for your precious time.
回答1:
(As already hinted by Bo Persson, this has (probably) to do with the so-called calling convention.
There is a nice explanation in Wikipedia x86 calling conventions.
Short summary: Different languages (resp. the compilers) may have different conventions in which order the arguments of a function are passed (e.g. on stack).
If you want to link object files where code is written in different languages, this can become an issue. Thus, some compilers have extensions to change the calling convention for function calls. (If nothing denoted the native is used, of course.)
Story Teller pointed out that (beside of the calling convention issue) there is something else in your sample code which is really suspicious.
The prototypes conv1()
and conv2()
in main
have unspecified argument lists. This is allowed in C (elaborated e.g. in SO: C: Unspecified number of parameters - void foo()). Unfortunately, it prevents detection of wrong calling.
conv1()
and conv2()
have two parameters each. However, both are called in main()
with one argument. This is undefined behavior.
(Thank you Story Teller to let me recognize this. The calling convention thing let me totally oversee this as well as the hint in Bo Perssons comment.)
来源:https://stackoverflow.com/questions/45434523/pascal-and-cdecl-keyword-in-c-language