什么是可变参数函数参数的自动型促销活动? [英] What are the automatic type promotions of variadic function arguments?

查看:103
本文介绍了什么是可变参数函数参数的自动型促销活动?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下code片断:

Consider the following code snippet:

#include <stdio.h>
#include <stdarg.h>

void display(int num, ...) {
    char c;
    int j;
    va_list ptr;
    va_start(ptr,num);
    for (j= 1; j <= num; j++){
        c = va_arg(ptr, char);
        printf("%c", c);

    }
    va_end(ptr);
}

int main() {
    display(4, 'A', 'a', 'b', 'c');
    return 0;
}

该计划使运行时错误,因为可变参数自动促进字符为int,我就在这种情况下,已经使用int类型。

The program gives runtime error because vararg automatically promotes char to int, and i should have used int in this case.

什么是当我使用可变参数的所有类型是允许的,怎么知道要使用哪种类型,避免这种运行时错误。

What are all types are permitted when I use vararg, how to know which type to use and avoid such runtime errors.

推荐答案

这是别人忘记提到另一种情况是指针类型,尤其关键的是 NULL 。因为这可能会扩大到 0 (无效*)0 (或其他一些奇怪的事情),你会不知道编译器列表中提出的 INT 无效* 。因为这些都可以有不同的宽度,这可能会导致令人讨厌的错误。

another case that the others forgot to mention are pointer types, critical is NULL in particular. Since this could expand to 0 or (void*)0 (or some other weird things) you will not know if the compiler puts an int or a void* in the list. Since these can have different width, this can lead to annoying bugs.

这篇关于什么是可变参数函数参数的自动型促销活动?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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