美文网首页
C++23: std::size_t 字面值常量

C++23: std::size_t 字面值常量

作者: fck_13 | 来源:发表于2021-01-24 19:44 被阅读0次

为什么?

举例:

#include <iostream>
#include <vector>
int main(){
    std::vector<int> vec{1, 2, 3};
    for(auto i = 0; i<vec.size(); i++){
        std::cout<<vec[i]<<std::endl;
    }
    return 0;
}

编译结果:

<source>: In function 'int main()':
<source>:8:22: warning: comparison of integer expressions of different signedness: 'int' and 'std::vector<int>::size_type' {aka 'long unsigned int'} [-Wsign-compare]
    8 |     for(auto i = 0; i<vec.size(); i++){
      |                     ~^~~~~~~~~~~

或者,我们将for(auto i = 0; i<vec.size(); i++){改成for(auto i = 0, s = vec.size(); i<s; i++){,得到编译结果

<source>: In function 'int main()':
<source>:8:9: error: inconsistent deduction for 'auto': 'int' and then 'long unsigned int'
    8 |     for(auto i = 0, s = vec.size(); i<s; i++){
      |         ^~~~
<source>:8:38: warning: comparison of integer expressions of different signedness: 'int' and 'long unsigned int' [-Wsign-compare]
    8 |     for(auto i = 0, s = vec.size(); i<s; i++){
      |                                     ~^~

第一种编译结果只是类型不匹配,第二种编译结果是auto自动推导出错。这给我们日常的编程工作带来一些不便。

怎么办?

这里借用cppreference的例子:

static_assert(std::is_same_v<decltype(0UZ), std::size_t>);
static_assert(std::is_same_v<decltype(0Z), std::make_signed_t<std::size_t>>);

对于符号的std::size_t,使用z或者Z作为后缀。
对于符号的std::size_t,使用zZuU的集合,即uzuZUz或者UZ

相关文章

  • C++23: std::size_t 字面值常量

    为什么? 举例: 编译结果: 或者,我们将for(auto i = 0; i

  • java语法基础

    常量 常量 : 在程序执行过程中,其值不能改变 Java中常量的分类 字面值常量 自定义常量 字面值常量的分类 字...

  • C++11的新特性

    空指针 nullptr 空指针的字面值常量,它的类型是std::nullptr_t(定义位于cstddef) 自动...

  • Java(常量的使用与概述)

    常量分类:a>字面值常量 b>自定义常量 A>字面值常量·字符串常量·整数 常量·小数常量·字符常量·布尔常量 ...

  • Java基础语法之常量

    1.Java中常量分类 字面值常量 自定义常量 2.字面值常量的分类 字符串常量 整数常量 小数常量 字符常量 布...

  • 2.2 变量

    一、学习要求 书籍参考章节: 第3章 知识点: 字面值 变量 常量 关键字 标识符 二、参考知识 字面值 字面值是...

  • JAVA中常量的概述和使用

    什么是常量 *在程序执行过程中值不可发生改变 Java中常量的分类 *字面值常量*自定义常量 字面值常量的分类 *...

  • Java学习笔记 2 - 基本数据类型和运算符

    1、常量在程序执行的过程中其值不可以发生改变Java中常量的分类:字面值常量、自定义常量字面值常量的分类:字符串常...

  • 3.常量

    #include using namespace std; //常量的定义方式 //1.#define 宏常量 /...

  • 常量与变量

    常量 定义:程序中固定不变化的值 常量分类 字面值常量 整数常量 1,2,3 小数常量3.14 布尔常量false...

网友评论

      本文标题:C++23: std::size_t 字面值常量

      本文链接:https://www.haomeiwen.com/subject/rczmzktx.html