C++库研究笔记——几个注意(size_t)

总之,用size_t 保证可移植性,保证其可以表示出最大需要表示的长度。

size_t 在stddef.h 中无命名空间

在<cstddef>有std::

size_t 与ptrdiff_t 要联合使用


When i is signed and size is unsigned, then i is converted to unsigned before the comparison is performed. This is part of what are called the usual arithmetic conversions.http://stackoverflow.com/questions/4311538/strange-behaviour-with-for-loop-and-size-t

unsigned int vs. size_t:

When to use std::size_t?

Difference between size_t and std::size_t

(ptrdiff_t 在64位下有更高的效率)




#include <iostream>
#include <stddef.h>

template <typename T, int N>
int size(T (&)[N])
{
    return N;
}

int main()
{
    int a[20];
    std::cout<<size(a)<<std::endl;


    std::cout<<"sizeof(short):"<<sizeof(short)<<std::endl;
    std::cout<<"sizeof(float):"<<sizeof(float)<<std::endl;
    std::cout<<"sizeof(double):"<<sizeof(double)<<std::endl;
    std::cout<<"sizeof(long):"<<sizeof(long)<<std::endl;
    std::cout<<"sizeof(size_t):"<<sizeof(size_t)<<std::endl;


    std::cout<<"sizeof(ptrdiff_t):"<<sizeof(ptrdiff_t)<<std::endl;  // error when not using #include <stddef.h>
    std::cout<<"sizeof(ptrdiff_t):"<<sizeof(std::ptrdiff_t)<<std::endl;
    return 0;
}

结果:

20
sizeof(short):2
sizeof(float):4
sizeof(double):8
sizeof(long):8
sizeof(size_t):8
sizeof(ptrdiff_t):8
sizeof(ptrdiff_t):8






  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值