C 语言的哪一部分处理类型检查?
What part of the C language handles type checking?
语言特性是否允许编译器检查内存中变量的类型,或者类型检查是否仅基于用于变量类型的关键字?
例如:
unsigned short n = 3;
int *p = &n;
int 和 short 都在内存中使用 4 个字节,但编译器无法将 short * 隐式转换为 int *。在这种情况下,编译器如何知道 n 不是 p 的有效地址?
每个表达式都有一个类型,最终派生自其中出现的变量和字面量的类型。 &n
的类型是unsigned short*
,不能用来初始化int*
类型的变量。这与检查内存无关,因此除了变量类型之外,它与上下文无关。
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?
这是一个很困惑的问题。编译器是实现语言的东西。因此,语言特性可能要求编译器做某些事情(为了使该特性工作),但它不会允许编译器做事。
一个"variable in memory"是一个运行时间概念。编译器仅在编译时参与:它将某种语言(源语言)的代码翻译成另一种语言(目标语言,通常是汇编代码/机器代码)。它发出指令(在执行时)保留内存并使用该内存存储值。但是在运行-时间,当程序真正执行时,编译器不再是画面的一部分,所以它不能检查任何东西。
在 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 进行类型检查。
语言特性是否允许编译器检查内存中变量的类型,或者类型检查是否仅基于用于变量类型的关键字?
例如:
unsigned short n = 3;
int *p = &n;
int 和 short 都在内存中使用 4 个字节,但编译器无法将 short * 隐式转换为 int *。在这种情况下,编译器如何知道 n 不是 p 的有效地址?
每个表达式都有一个类型,最终派生自其中出现的变量和字面量的类型。 &n
的类型是unsigned short*
,不能用来初始化int*
类型的变量。这与检查内存无关,因此除了变量类型之外,它与上下文无关。
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?
这是一个很困惑的问题。编译器是实现语言的东西。因此,语言特性可能要求编译器做某些事情(为了使该特性工作),但它不会允许编译器做事。
一个"variable in memory"是一个运行时间概念。编译器仅在编译时参与:它将某种语言(源语言)的代码翻译成另一种语言(目标语言,通常是汇编代码/机器代码)。它发出指令(在执行时)保留内存并使用该内存存储值。但是在运行-时间,当程序真正执行时,编译器不再是画面的一部分,所以它不能检查任何东西。
在 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 进行类型检查。