I have this code:
#include <stdint.h>
void something(float a);
int main()
{
uint8_t a = 28;
something(a);
return 0;
}
void something(float a)
{
printf("%f\n", a);
}
I am using a similar function to log variables of different types to a file and I would like to get an error/warning message since I am calling function something with a wrong argument type (uint8_t instead of float).
How can I achieve this?
The old school trick is to change the function to use pointers, since pointers in C have much stricter typing rules than integers and floating point.
#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("%f\n", *a);
}
The modern C version:
#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("%f\n", a);
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments