跳转至

c#

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.

The C Memory Model

Pointers present us with a certain abstraction of the environment and state in which our program is executed, the C memory model. We may apply the unary operator & to (almost) all objects to retrieve their address and use it to inspect and change the state of our execution.

C Basic Types - Binary Representions

Values have a type and a binary representation.

The binary representation of a type is a model that describes the possible values for that type. It is not the same as the in-memory object representation that describes the more or less physical storage of values of a given type.

TAKEAWAY 5.49

TAKEAWAY 5.49 The same value may have different binary representations.

C语言标准与实现之整数类型

在 C 语言刚刚被设计出来的时候,一共只有两种整数类型 —— charint。C89 引入了两种新的整数类型 —— shortlong,C99 再增加一种整数类型 —— long long。

后来,随着 C 语言的进一步发展,K&R C 引入了无符号整数的概念以及 unsigned 关键字。char 既不属于标准带符号整数类型也不属于标准无符号整数类型,它属于历史遗物。

C89 引入 signed 关键字后,可显式声明 signed char,明确表达最小的标准带符号整数类型。

为什么 getchar() 返回的类型是 int,而不是 char?

C Data Types

A C program, whatever its size, consists of functions and variables. A function contains statements that specify the computing operations to be done, and variables store values used during the computation.

在 C 程序里,函数(function)就是指令,变量(variable)就是数据。数据类型定义了变量的存储和访问属性,约束了其大小边界(size/boundary)、取值范围(value range)、解释呈现(interpretation/representation)和可操作集(operation set)。