什么是可变参数函数参数的自动型促销活动? [英] What are the automatic type promotions of variadic function arguments?
问题描述
考虑以下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屋!