C语言之可变参数类型提升问题及解决
C语言可变参数类型提升
在C语言里面,可变参数是一个特殊的存在,它允许开发者不用显示指定参数形式,通过...来表示这段参数是可变的,在内部在通过va_list来获取这些参数,但是这里有一个需要注意的事情,va_list属于编译器私有实现,它不是单纯通过地址偏移来拿参数,因为不同的平台传递参数是不一样的,有的平台用寄存器,而有的则是用栈,参数多了可能寄存器+栈组合,所以这类是不固定的,因此它必须结合va_arg来获取参数,默认i情况下C语言对可变参数会进行类型提升,这么做的原因主要是历史原因,从8位演化到64位架构,为了统一对齐需要对一些小类型做提升,这个逻辑跟结构体对齐是一样的。
下面是一段示例代码
#include <stdio.h>
#include <stdarg.h>
static void wrong_read(const char *tag, ...)
{
va_list ap;
va_start(ap, tag);
char c = va_arg(ap, char);
short s = va_arg(ap, short);
float f = va_arg(ap, float);
va_end(ap);
printf("[%s] c=%d s=%d f=%f\n", tag, c, s, f);
}
int main(void)
{
char c = 65;
short s = 1234;
float f = 3.14f;
wrong_read("wrong", c, s, f);
return 0;
}
这段代码会出现段错误
➜ ~ ./a.out
[1] 831819 illegal hardware instruction (core dumped) ./a.out
并且上述代码其实在构建的时候就会出现日志报错:
➜ ~ gcc test.c
In file included from test.c:2:
test.c: In function ‘wrong_read’:
test.c:20:25: warning: ‘char’ is promoted to ‘int’ when passed through ‘…’
20 | char c = va_arg(ap, char);
| ^
test.c:20:25: note: (so you should pass ‘int’ not ‘char’ to ‘va_arg’)
test.c:20:25: note: if this code is reached, the program will abort
test.c:21:26: warning: ‘short int’ is promoted to ‘int’ when passed through ‘…’
21 | short s = va_arg(ap, short);
| ^
test.c:21:26: note: if this code is reached, the program will abort
test.c:22:26: warning: ‘float’ is promoted to ‘double’ when passed through ‘…’
22 | float f = va_arg(ap, float);
| ^
test.c:22:26: note: if this code is reached, the program will abort
注意看重点这段
warning: ‘char’ is promoted to ‘int’ when passed through ‘...’'
这里其实已经说明了char被提升到了int类型,所以正确的解析是使用int:
int c = va_arg(ap, int); int s = va_arg(ap, int); double f = va_arg(ap, double);
其实可以看到不光是char,连short、float都已经被提升了,对于可变参数规范里是要求小类型变大类型,char本质上可以理解为一个8bit的整数、字类型、小整数类型,它会被提升到int,short会被提升到int,float会被提升到double,每个基本类型至少会被提升到最大类型上,包括bool也会被提升到int,可变参数提升的类型范围仅限于char、short、float、bool这一类,因此在进行可变参数开发时需要注意这一点,否则会导致程序莫名崩溃。
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。


最新评论