What are the automatic type promotions of variadic function arguments?

后端 未结 3 1596
盖世英雄少女心
盖世英雄少女心 2020-12-11 06:06

Consider the following code snippet:

#include 
#include 

void display(int num, ...) {
    char c;
    int j;
    va_list ptr;         


        
相关标签:
3条回答
  • 2020-12-11 06:12

    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.

    0 讨论(0)
  • 2020-12-11 06:18

    While using va_arg the char is promoted to int. 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.

    like: c = (char) va_arg(ap, int);

    for the complete example please see:

    http://en.cppreference.com/w/cpp/language/variadic_arguments

    0 讨论(0)
  • 2020-12-11 06:24

    You can use any standard type with va_arg except char, signed char, unsigned char, short, unsigned short, _Bool, and float. It's possible that an implementation defines additional nonstandard types that also have integer conversion rank lower than int, 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.

    0 讨论(0)
提交回复
热议问题