向C函数提供错误的参数类型时抛出错误/警告
我有这个代码:
#include <stdint.h>
void something(float a);
int main()
{
uint8_t a = 28;
something(a);
return 0;
}
void something(float a)
{
printf("%fn", a);
}
我使用了类似的功能登录不同类型的变量到一个文件,我想因为我调用函数来得到一个错误/警告信息的东西有错误的参数类型(uint8_t,而不是浮点)。
我怎样才能做到这一点?
回答
老派的技巧是将函数更改为使用指针,因为 C 中的指针具有比整数和浮点数更严格的类型规则。
#include <stdio.h>
#include <stdint.h>
void something(const float* a);
int main()
{
uint8_t a = 28;
/* gcc -std=c11 -pedantic-errors */
something(&a); // error: passing argument 1 of 'something' from incompatible pointer type
something(a); // error: passing argument 1 of 'something' makes pointer from integer without a cast
return 0;
}
void something(const float* a)
{
printf("%fn", *a);
}
现代 C 版本:
#include <stdio.h>
#include <stdint.h>
void something_float (float a);
#define something(x) _Generic((x), float: something_float)(x)
int main()
{
uint8_t a = 28;
something(a); // error: '_Generic' selector of type 'unsigned char' is not compatible with any association
return 0;
}
void something_float (float a)
{
printf("%fn", a);
}