向某人解释为什么类型转换不会在编译时自动完成
最近,当我为 Fortran 程序员撰写 C 语言简介时,其中一位 Fortran 程序员问我有关类型转换的问题。 对他来说,在 C 中你必须显式地转换变量而不是让编译器自动为你做这件事,这并没有什么意义。
事实上,我很难证明这是一件好事,因为它有助于避免无意的错误。
你会如何证明这一点?
Recently, while I was writing a brief introduction to C for Fortran programmers, one of said Fortran programmers asked me about type casting.
To him, it did not really make sense that in C you have to explicitly cast variables instead of having the compiler do it for you automatically.
I actually had a bit of hard time making my point that this is good thing because it helps in avoiding unintentional errors.
How would you justify this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
C 不需要强制转换。转换大部分是在编译时自动完成的。
这有效并且是惯用的 C
程序中太多的转换表明程序员(可能)使用 C++ 编译器来编译 C 源文件。一些(很多?)强制转换的使用是完全错误的。
C does not need casts. Conversions are mostly done automatically at compile time.
This works and is idiomatic C
Too many casts in a program indicate the programmer was (probably) using a C++ compiler to compile a C source file. Some (many??) uses of casts are just plain wrong.
更一般地说(对于 pmg 的回答),有时类型转换可以安全地完成,有时则不能。此外,有时它可能会做一些与您想要的不同的事情。
当类型转换可能指示程序员错误时,需要。指针就是一个很好的例子。如果您有一个指向字符的指针并将其分配给一个指向整数的指针,那么可能有充分的理由这样做,但如果不小心这样做,当您取消引用该指针时(同样,在一些非常旧的平台,指针的大小不同!)。
关于自动类型转换何时发生以及如何发生有广泛的规则。有些人宁愿放弃一切,也不愿学习规则,以确保不会发生任何意外。
More generally (to pmg's answer) there are times when the type conversion can be done safety and there are times when it cannot. Also, there are times when it may do something other than what you want.
Type casting is required when it may indicate programmer error. Pointers are a good example of this. If you have a pointer to a character and assign it to a pointer to an integer, there might be good reasons to do this, but if done accidentally, you could well get bus errors or invalid results when you dereference that pointer (also, on some very old platforms, the sizes of the pointers were different!).
There are extensive rules on when automatic type conversion happens and how it happens. Some people would rather cast everything than learn the rules, to ensure that nothing undesired happens.