在if语句中首先放置常量的原因是什么? [英] What's the reasoning behind putting constants in if statements first?
问题描述
我在看一些例子C ++代码的硬件接口我正在使用,并注意到许多语句沿以下行:
I was looking at some example C++ code for a hardware interface I'm working with and noticed a lot of statements along the following lines:
if ( NULL == pMsg ) return rv;
我相信我听说有人说把恒定放在第一位是个好主意,这是为什么?只是这样,如果你有一个大的声明,你可以很快看到你正在比较或有更多的它吗?
I'm sure I've heard people say that putting the constant first is a good idea, but why is that? Is it just so that if you have a large statement you can quickly see what you're comparing against or is there more to it?
推荐答案
因此,你不要将比较(==)与赋值(=)混合。
So that you don't mix comparison (==) with assignment (=).
如你所知,你不能分配一个常量。如果你尝试,编译器会给你一个错误。
As you know, you can't assign to a constant. If you try, the compliler will give you an error.
基本上,它是防御性编程技术之一。保护自己免受伤害。
Basically, it's one of defensive programming techniques. To protect yourself from yourself.
这篇关于在if语句中首先放置常量的原因是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!