C语言中的Pascal和cdecl关键字 [英] Pascal and cdecl keyword in C language

查看:306
本文介绍了C语言中的Pascal和cdecl关键字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

面试问题在我的脑海中引起了极大的困惑,即让我们看一下这个程序

#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);
}

输出为

25 0

0 25

但是为什么呢?以及如何?

您能简要地向我解释一下,因为我不理解UGC书中提到的该程序.

请帮助我更好地理解这个概念,以便为面试做更好的准备.

感谢您的宝贵时间.

解决方案

(如 Bo Persson 所暗示,这(可能)与所谓的通话惯例有关.

Wikipedia x86调用约定中有一个很好的解释.

简短摘要:不同的语言(分别是编译器)可能具有不同的约定,这些约定按顺序传递函数的参数(例如,在堆栈上).

如果要链接使用不同语言编写代码的目标文件,这可能会成为问题.因此,某些编译器具有扩展功能,可以更改函数调用的调用约定. (当然,如果未使用任何表示本机的内容,则表示使用.)


Story Teller 指出(在调用约定问题之外)示例代码中还有其他内容真的很可疑.

main中的原型conv1()conv2()具有未指定的参数列表.这在C语言中是允许的(例如在 SO中详细说明:C:未指定的参数数量-void foo()).不幸的是,它可以防止检测到错误的呼叫.

conv1()conv2()分别具有两个参数.但是,两者都在main()中用一个参数调用.这是未定义的行为.

(谢谢您的讲故事的人,让我认识到这一点.调用约定让我完全监督了这一点以及Bo Perssons评论中的提示.)

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.

解决方案

(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.)

这篇关于C语言中的Pascal和cdecl关键字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆