首先在"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 compiler will give you an error.
基本上,它是防御性编程技术之一.为了保护自己免受伤害.
Basically, it's one of defensive programming techniques. To protect yourself from yourself.
这篇关于首先在"if"语句中添加常量的背后原因是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!