C语言进阶

注: 本篇博客是我在码农周刊中看到的文章,原文地址

http://pfacka.binaryparadise.com/articles/guide-to-advanced-programming-in-C.html


由于是英文,我相当于理解和学习一下原文的内容,谢谢

1、sizeof() 的使用

#include <stdio.h>

int main(int argc, char *argv[])
{
    long i = -1;

    if(i < sizeof(i))
    {
        printf("ok\n");
    }
    else
    printf("error\n");

    return 0;
}

编译输出后 打印结果为:   error, 由于sizeof 返回值时unsigned int的 故i和sizeof(i) 运算要做强制类型转换, i转换后编程比较大的值,故结果输出为 error。

英文原文为:"If the operand that has unsigned integer type has rank greater orequal to the rank of the type of the other operand, then the operand withsigned integer type is converted to the type of the operand with unsignedinteger type."


2、C语言在做跨平台编辑的时候最后能够对 变量类型做宏定义, C语言对各个变量类型只是定义了最小长度,所以在有些平台他所使用的变量类型长度不是一些默认的 如 long on Linux is 64-bit whereas on 64-bit Windows it is 32-bit.(long 类型在 64位linux长度为 64位 但在windows 64位系统上时 32位长度)所以涉及到跨平台时最好使用变量类型宏定义头文件stdint.h(C99标准)提供了一些定义的方法

  • with exactly specified size: uint8_t uint16_t, int32_t, etc.        确定长度的
  • smallest type with at least specified size: uint_least8_t, uint_least16_t, int_least32_t, etc.      确定最小长度的
  • most efficient type with at least specified size: uint_fast8_t, uint_fast16_t, int_fast32_t, etc.   确定最小长度的

但是这个定义的方法也是有缺陷的,如程序

uint32_t sum()
{
    uint16_t a = 65535;
    uint16_t b = 1;
    return a+b;
}
在 16位平台上 值是 0 (16位平台上uint32也是16位长度 )在32位平台上是 65536,

3、




  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值