1. if(i)
void check_positive(int a)
{
if(a) printf("I am positive %d\n",a);
else printf("I am negative %d\n",a);
}
int main(void)
{
int a = 9;
int b = -1;
check_positive(a);
check_positive(b);
return 0;
}
What's the result?
I am positive 9
I am positive -1
Tip: if(a) means if(a == 0)
2. write a self_printf() and check its parameters as printf()
int uart_printf(const char *format, ...) __attribute__((__format__(printf, 1, 2)));
3. put all variables declaration at the top of a function
Because in the middle is not a good style, and sometimes compiler(C standard) could report error/warning.
4. printf() paramter check
int main(void)
{
uint64_t l_64=0x123456789abcdef0;
printf("64 bit high %x, low %x\n",l_64>>32,l_64&0xFFFFFFFF);
return 0;
}
When build, we will get warnings as following.
$ gcc -o print print.c
print.c: In function ‘main’:
print.c:56:26: warning: format ‘%x’ expects argument of type ‘unsigned int’, but argument 2 has type ‘uint64_t’ {aka ‘long unsigned int’} [-Wformat=]
56 | printf("64 bit high %x, low %x\n",l_64>>32,l_64&0xFFFFFFFF);
| ~^ ~~~~~~~~
| | |
| unsigned int uint64_t {aka long unsigned int}
| %lx
print.c:56:34: warning: format ‘%x’ expects argument of type ‘unsigned int’, but argument 3 has type ‘uint64_t’ {aka ‘long unsigned int’} [-Wformat=]
56 | printf("64 bit high %x, low %x\n",l_64>>32,l_64&0xFFFFFFFF);
| ~^ ~~~~~~~~~~~~~~~
| | |
| unsigned int uint64_t {aka long unsigned int}
| %lx
This warning is helpful for us to correct the code. Here is a compile option can ignore this warning.
$ gcc -Wformat=0 -o print print.c