Skip to content

cpp#

volatile in C/C++

volatile (computer programming) - Why is volatile needed in C?

volatile in C actually came into existence for the purpose of not caching the values of the variable automatically. It will tell the compiler not to cache the value of this variable. So it will generate code to take the value of the given volatile variable from the main memory every time it encounters it. This mechanism is used because at any time the value can be modified by the OS or any interrupt. So using volatile will help us accessing the value afresh every time.

Struct Alignment Specify

在上一篇《Struct Alignment Rule》中,我们梳理了结构体存储布局的“地址边界对齐限制”规则。
本篇介绍通过编译器 gcc/msvc 提供的扩展特性及 C/C++ 提供的一些语言特性来修改默认的对齐参数,并测试分析其作用效果。

  1. The packed attribute specifies that a structure member should have the smallest possible alignment.
  2. The aligned attribute specifies a minimum alignment for the variable or structure field, measured in bytes.
  3. -fpack-struct[=n]/#pragma pack(n) specifies the maximum alignment, structure members can potentially be unaligned.

Struct Alignment Rule

An object doesn't just need enough storage to hold its representation. In addition, on some machine architectures, the bytes used to hold it must have proper alignment for the hardware to access it efficiently.

Where alignment most often becomes visible is in object layouts: sometimes structs contain "holes" to improve alignment.

C/C++ Memory Alignment

One of the low-level features of C/C++ is the ability to specify the precise alignment of objects in memory to take maximum advantage of a specific hardware architecture. By default, the compiler aligns class and struct members on their size value.

Binary —— Bitset & Bytes

所谓数制是指计数的方法。对于有10根手指的人来来说,使用十进制表示法是很自然的事情,现代计算机则采用的是二进制系统,存储和处理的信息以二值信号表示。

一串二进制数码按照固定长度(8)组合出有意义的基本存储单位——字节,多个字节(1,2,4,8)可以组合出基本算术单元 char,short,int/float,long/double,或复合类型和用户自定义类型。

在计算机内存或磁盘上,指令和数据没有任何区别,都是二进制信息。CPU 在工作的时候把有的信息解析为指令,有的信息解读为数据,为同样的信息赋予了不同的意义。

这涉及到 Abstract State Machine

  • a value : what state are we in
  • the type : what this state represents
  • the representation : how state is distinguished

C++ Data Types

Every name and every expression has a type that determines the operations that may be performed on it.

Types built out of the built-in types using C++'s abstraction mechanisms are called user-defined types. They are referred to as structures, classes and enumerations.