可变参数函数参数的自动类型提升是什么?
考虑以下代码片段:
#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;
}
程序给出运行时错误,因为 vararg 自动将 char 提升为 int,在这种情况下我应该使用 int。
当我使用 vararg 时,哪些类型是允许的,如何知道使用哪种类型并避免此类运行时错误。
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;
}
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
其他人忘记提及的另一种情况是指针类型,特别是 NULL 。由于这可能会扩展为
0
或(void*)0
(或其他一些奇怪的东西),因此您将不知道编译器是否放置了int
或列表中的void*
。由于它们可以具有不同的宽度,这可能会导致恼人的错误。another case that the others forgot to mention are pointer types, critical is
NULL
in particular. Since this could expand to0
or(void*)0
(or some other weird things) you will not know if the compiler puts anint
or avoid*
in the list. Since these can have different width, this can lead to annoying bugs.您可以在
va_arg
中使用任何标准类型,除了char
、signed char
、unsigned char
、short< /code>、
无符号短值
、_Bool
和float
。实现可能会定义其他非标准类型,这些类型的整数转换等级也低于 int,或者类似的非标准小浮点类型,但除非您打算使用,否则您不需要了解这些类型因此,出于实用目的,我给出的清单是完整的。You can use any standard type with
va_arg
exceptchar
,signed char
,unsigned char
,short
,unsigned short
,_Bool
, andfloat
. It's possible that an implementation defines additional nonstandard types that also have integer conversion rank lower thanint
, or likewise nonstandard small floating-point types, but you would not need to be aware of these unless you intend to use them, so for practical purposes the list I gave is complete.使用 va_arg 时,
char
会提升为int
。还有其他类型(@R..给出的列表)被提升。因此,为了将其读取为
char
,您必须进行类型转换。有关完整列表,请参阅以下位置中的“默认转换”部分:
http://en .cppreference.com/w/cpp/language/variadic_arguments
While using va_arg the
char
is promoted toint
. There are other types(the list given by @R..) which are promoted.so in order to read it as a
char
you have to do typecast.For a complete list, please see the 'Default conversions' section in:
http://en.cppreference.com/w/cpp/language/variadic_arguments