Tips of C programming

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

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值