C++学习笔记九:值,常量,常表达式和常初始化
1. 值:
Literal: Data that is directly represented in code without going through some other variable stored in memory.
值: 直接在代码中表示的数据,无需通过内存中存储的其他变量。值不在内存中进行存储,而是直接在二进制的可执行文件中产生。
1.1 整型
//Literal types : u and l combinations for unsigned and long.(大小写都可)
unsigned char unsigned_char {53u};// 555U would fail because of narrowing
//2 Bytes
short short_var {-32768} ; // No special literal type for short)
short int short_int {455} ; // No special literal type for short
signed short signed_short {122}; // No special literal type for short
signed short int signed_short_int {-456}; // No special literal type for short
unsigned short int unsigned_short_int {5678U };
// 4 Bytes
const int int_var {55} ; //
signed signed_var {66}; //
signed int signed_int {77}; //
unsigned int unsigned_int {555U}; //
//4 or 8 Bytes
long long_var {88L}; // 4 OR 8 Bytes
long int long_int {33L};
signed long signed_long {44l};
signed long int signed_long_int {44l};
unsigned long int unsigned_long_int {555ul};
//8 Bytes
long long long_long {888ll};// 8 Bytes
long long int long_long_int {999ll};
signed long long signed_long_long {444ll};
signed long long int signed_long_long_int{1234ll};
//Grouping Numbers : C++14 and onwards
unsigned int prize {1'500'00'0u};
std::cout << "The prize is : " << prize << std::endl;
std::cout << " signed_long_long_int : " << signed_long_long_int << std::endl;
//Narrowing errors
//Possible narrowing errors are cought by the braced initializer method.
//Assignment and functional don't catch that.
//unsigned char distance {555u}; //Error [0~255]
//unsigned int game_score {-20}; //Error
1.2 十六进制赋值:
//With number systems - Hex : prefix with 0x
unsigned int hex_number{ 0x22BU}; // Dec 555
int hex_number2 {0x400};// Dec 1024
std::cout << std::hex << "The hex number is : " << hex_number << std::endl;
std::cout << std::dec << "The hex number2 is : " << hex_number2 << std::endl;
//review: direct output only gives devimal number, use std::hex to get hex output
//Representing colors with hex
int black_color {0xffffff};
std::cout << "Black color is : " << std::dec << black_color << std::endl;
1.3 八进制赋值:
//Octal literals : prefix with 0
int octal_number {0777u}; // 511 Dec
std::cout << std::oct << "The octal number is : " << octal_number << std::endl;
//!!BE CAREFUL NOT TO PREFIX YOUR INTEGERS WITH 0 IF YOU MEAN DEC
int error_octal {055};// This is not 55 in memory , it is 45 dec
std::cout << "The erronous octal number is : " << error_octal << std::endl;
1.4 二进制赋值
//Binary literals
unsigned int binary_literal {0b11111111u};// 255 dec
std::cout << "The binary literal is : " << binary_literal << std::endl;
1.5 其他类型赋值
char char_literal {'c'};
int number_literal {15};
float fractional_literal {1.5f}; //不加f默认只是double类型
std::string string_literal {"Hit the road"};
2. 常量
const: A read only variable. Cannot assign data to it.
常量:是一个只读值,不能赋值,CPU并没有常量的概念,是程序层在constant对变量修饰后导致变量只读的属性。一般用于定义在整个程序运行周期内都不想被改变的量。常量在声明的时候必须赋值。
const int age {34};
const float height {1.67f};
//age = 55; // Can't modify
//height = 1.8f;
3. 常表达式
constexpr: A constant that has the potential to be evaluated at compile time
3.1 程序的产生过程:
IDE Code -> Compile time(从代码生成二进制可执行文件) -> Run time
如果可能的话,把复杂的计算放到编译中去做(Compile time computations),一旦编译完成,在运行时可以直接调用编译生成的结果。c++11之后引入的特性。
可执行二进制文件的一般执行过程:
initialization->Constexpr computation->Runtime computation
改进后:
initialization->Runtime computation
3.2 举例:
constexpr int SOME_LIB_MAJOR_VERSION {1237};
constexpr int eye_count {2};
constexpr double PI {3.14};
//eye_count = 4; //error
std::cout << "eye count : " << eye_count << std::endl;
std::cout << "PI : " << PI << std::endl;
// int leg_count {2}; // Non constexpr
// leg_count is not known at compile time
// constexpr int arm_count{leg_count}; // Error, cannot initialize a compile
// time variable with a runtime variable
constexpr int room_count{10};
constexpr int door_count{room_count};// OK
const int table_count{5};
constexpr int chair_count{ table_count * 5};// Works
static_assert( SOME_LIB_MAJOR_VERSION == 123); //compile time check
// int age = 5;
// static_assert( age == 5); //不能检查非constant变量
std::cout << "App doing its thing..." << std::endl;
4. 常初始化(C++20特性)
constinit: A variable that should be initialized with a constant or literal at compile time
指定变量必须拥有静态初始化,即零初始化与常量初始化,否则程序非良构。这种变量必须是静态的或者是全生命周期的variables with static or thread storage duration。
什么是静态变量:When you declare a variable in a function, the static keyword specifies that the variable retains its state between calls to that function. When you declare a data member in a class declaration, the static keyword specifies that one copy of the member is shared by all instances of the class.
可以帮助解决在主函数外的初始化问题。必须初始化。const和constinit可以结合使用,const和constexpr不可以结合使用。const init不说明变量是常量,只是说明编译器强制其在编译过程中初始化。
#include <iostream>
const int val1 {33};
constexpr int val2{34};
int val3 {35}; // Run time value
constinit int age = 88; // This is initialized at compile time
const constinit int age1 {val1}; // const and constinit can be combined
constinit int age2 {age1}; // Initializing with age would lead to a compiler error
// age is not const
//constinit int age3 {val3}; // Error : val3 is evaluated at run time
// can't const initialize age3
const constinit double weight {33.33};
//constexpr constinit double scale_factor{3.11};// Can't combine constexpr and constinit
int main(){
//constinit double height{1.72}; //compiler error, not static or thread storage duration
std::cout << "age : " << age << std::endl;
std::cout << "age1 : " << age1 << std::endl;
std::cout << "age2 : " << age2 << std::endl;
age =33; // Can change a const init variable
std::cout << "age : " << age << std::endl;
//Combining const and constinit
std::cout << "weight : " << weight << std::endl;
//weight = 44.44; // Compiler error
return 0;
}
C++学习笔记九:值,常量,常表达式和常初始化的更多相关文章
- 多线程学习笔记九之ThreadLocal
目录 多线程学习笔记九之ThreadLocal 简介 类结构 源码分析 ThreadLocalMap set(T value) get() remove() 为什么ThreadLocalMap的键是W ...
- Go语言学习笔记九: 指针
Go语言学习笔记九: 指针 指针的概念是当时学C语言时了解的.Go语言的指针感觉与C语言的没啥不同. 指针定义与使用 指针变量是保存内存地址的变量.其他变量保存的是数值,而指针变量保存的是内存地址.这 ...
- C#学习笔记之值类型与引用类型
[TOC] C#学习笔记之值类型与引用类型 1.值类型与引用类型 1.1 深层区别 值类型与引用类型有不同的内存分布,这导致了不同的内存管理机制: 值类型由OS负责内存管理 引用类型由垃圾回收器(GC ...
- MDX导航结构层次:《Microsoft SQL Server 2008 MDX Step by Step》学习笔记九
<Microsoft SQL Server 2008 MDX Step by Step>学习笔记九:导航结构层次 SQL Server 2008中SQL应用系列及BI笔记系列--目录索 ...
- python3.4学习笔记(九) Python GUI桌面应用开发工具选择
python3.4学习笔记(九) Python GUI桌面应用开发工具选择 Python GUI开发工具选择 - WEB开发者http://www.admin10000.com/document/96 ...
- Go语言学习笔记三: 常量
Go语言学习笔记三: 常量 定义常量 常量就是在声明后不能再修改的量. const x int = 100 const y string = "abc" const z = &qu ...
- go微服务框架kratos学习笔记九(kratos 全链路追踪 zipkin)
目录 go微服务框架kratos学习笔记九(kratos 全链路追踪 zipkin) zipkin使用demo 数据持久化 go微服务框架kratos学习笔记九(kratos 全链路追踪 zipkin ...
- Introduction to 3D Game Programming with DirectX 12 学习笔记之 --- 第四章:Direct 3D初始化
原文:Introduction to 3D Game Programming with DirectX 12 学习笔记之 --- 第四章:Direct 3D初始化 学习目标 对Direct 3D编程在 ...
- C#线程学习笔记九:async & await入门二
一.异步方法返回类型 只能返回3种类型(void.Task和Task<T>). 1.1.void返回类型:调用方法执行异步方法,但又不需要做进一步的交互. class Program { ...
- Python学习笔记九
Python学习笔记之九 为什么要有操作系统 管理硬件,提供接口. 管理调度进程,并且将多个进程对硬件的竞争变得有序. 操作系统发展史 第一代计算机:真空管和穿孔卡片 没有操作系统,所有的程序设计直接 ...
随机推荐
- DORA指标:公司业务成果的“占卜师”
2009 年,受 John Allspaw 和 Paul Hammonds 在 Velocity 上演讲的启发,Patrick Debois 组织了一次名为"DevOps Days" ...
- 通过提示大语言模型进行个性化推荐LLM-Rec: Personalized Recommendation via Prompting Large Language Models
论文原文地址:https://arxiv.org/abs/2307.15780 本文提出了一种提示LLM并使用其生成的内容增强推荐系统的输入的方法,提高了个性化推荐的效果. LLM-Rec Promp ...
- 一款广受社区好评的 WAF
大家好,我是 Java陈序员,我们有时会搭建一个属于自己的网站,但是自建网站很容易被收到攻击,今天给大家介绍一款简单免费好用的 WAF 网站防护工具. WAF 是 Web Application Fi ...
- Codechef - Maximize Colours(IQ)
题目大意 有红绿蓝三种颜色,三种颜色当中任意两个颜色混合都可以产生出一个新的颜色(然而混合产生的颜色不能与任何其它的颜色进行混合).输入三个整数,分别代表红色,绿色,蓝色的颜色个数(每次混合各消耗 ...
- 使用SemanticKernel 进行智能应用开发(2023-10更新)
以OpenAI 的ChatGPT 所掀起的GenAI 快速创新浪潮,其中连接LLM 和 应用之间的桥梁的两大开源项目:LangChain[1]和Semantic Kernel[2] ,在半年前写过一篇 ...
- 算法1:寻找完数(JS)
任务一:寻找完数 打印10000以内的完数 完数:与自己所有因子之和相等的数. 1 let sum = 0, i, j; // 定义变量sum.i和j 2 3 for (i = 1; i < 1 ...
- C静态库的创建与使用--为什么要引入静态库?
C源程序需要经过预处理.编译.汇编几个阶段,得到各自源文件对应的可重定位目标文件,可重定位目标文件就是各个源文件的二进制机器代码,一般是.o格式.比如:util1.c.util2.c及main.c三个 ...
- CF1368B
题目简化和分析: 因为要求长度最小,所以我们每个字符就应该发挥最大的价值,不会有没有作用的字符. 设有 \(x_1\) 个 \(c\) ,\(x_2\) 个 \(o\) ,\(x_3\) 个 \(d\ ...
- 错误记录-FileStream访问被拒绝
简介: 问题:因项目需要,软件需要读取授权文件中的密文与本机验证码做一定的逻辑比对,使用FileStream实现文件的读取,在本机调试没问题,但在其他同事电脑上有一些出现授权一直不通过的情况. --M ...
- 最新 2023.2 版本 WebStorm 永久破解教程,WebStorm 破解补丁永久激活(亲测有效)
最近 jetbrains 官方发布了 2023.2 版本的 IDEA,之前的激活方法并不支持这个新的版本. 下面是最新的激活教程,激活步骤和之前是类似的,只是换用了不同的补丁文件. 本教程支持 Jet ...