gpt4 book ai didi

c - C 语言的哪一部分处理类型检查?

转载 作者:太空宇宙 更新时间:2023-11-04 06:54:43 25 4
gpt4 key购买 nike

语言特性是否允许编译器检查内存中变量的类型,或者类型检查仅基于用于变量类型的关键字?

例如:

unsigned short n = 3;
int *p = &n;

int 和 short 都在内存中使用 4 个字节,但编译器无法将 short * 隐式转换为 int *。在这种情况下,编译器如何知道 n 不是 p 的有效地址?

最佳答案

Does a language feature allow the compiler to check the type of a variable in memory, or is type checking based only on the keyword used for the variable type?

这是一个很困惑的问题。编译器是实现语言的东西。因此,语言功能可能要求编译器做某些事情(为了使该功能工作),但它不会允许编译器做某些事情。 p>

“内存中的变量”是一个运行时概念。编译器仅在编译时参与:它将某种语言(源语言)的代码翻译成另一种语言(目标语言,通常是汇编代码/机器代码)。它发出指令(在执行时)保留内存并使用该内存存储值。但在运行时,当程序实际执行时,编译器不再是画面的一部分,因此它无法检查任何东西。

在 C 中,类型在编译时检查。编译器知道字面量的类型(例如 42 是一个 int"hello" 是一个 char [6]),并且它知道你声明的所有内容的类型(因为它必须解析声明),包括变量。类型检查和类型转换规则与类型的大小无关。

例如:

short int a = 42;
double b = a; // OK, even though commonly sizeof a == 2 and sizeof b == 8

另一方面:

signed char c;
char *p = &c; // error, even though commonly char and signed char have the same
// size, representation, and range of possible values

完全可以在不实际生成任何代码的情况下对 C 进行类型检查。

关于c - C 语言的哪一部分处理类型检查?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46623189/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com