Embedded projects use the C language structure segment feature to assert the validity of macro validation data range
- 2020-06-12 10:08:06
- OfStack
We won't talk much about the features of bit segments, but read the corresponding C language books for more information.
Today we introduce assertion macros. What is an assertion macro? An assertion macro can be thought of as an implementation of a macro that verifies the validity of a data range. Let's look at the code:
#include <stdio.h>
// Structural body segment
#define CHECK(x) sizeof(struct {unsigned:(-!!(x));})
// Check that the constants are in 1 If not, compile error
// Such as the definition 1 a 0 to 1000 If passed in xxx Less than 0 Or greater than 1000 , the compiler detects an error
#define DEFI(a , xxx) a = CHECK(xxx<0) + CHECK(xxx>1000) + xxx
int main(void)
{
int a ;
DEFI(a , 2000) ;
printf("a:%d \n" , a);
return 0 ;
}
Operation results:
Compile error because the range of 2000 is not 0~1000:
If we change it to a valid data range, say 1000, let's look at the results:
#include <stdio.h>
// Structural body segment
#define CHECK(x) sizeof(struct {unsigned:(-!!(x));})
// Check that the constants are in 1 If not, compile error
// Such as the definition 1 a 0 to 1000 If passed in xxx Less than 0 Or greater than 1000 , the compiler will find an error
#define DEFI(a , xxx) a = CHECK(xxx<0) + CHECK(xxx>1000) + xxx
int main(void)
{
int a ;
DEFI(a , 1000) ;
printf("a:%d \n" , a);
return 0 ;
}
This approach can be used in the development of embedded projects, remind yourself to always pay attention to the range of data types, I think this is a very good programming aid check.
conclusion