c++ styleguide: why to have non-lvalues on the lef

2019-01-15 18:46发布

In one C++ coding style guide, I found one particular recommendation (page 41, recommendation number 53):

Always have non-lvalues on the left side (0 == i instead of i == 0).

And I don't uderstand what is this good for? Are to sticking to this practice?

I'm not and I don't know why is his a good practice. The only advantage I can think of is that is will avoid mistaking an unintentional assignment with a comparison (if (foo = 0){} versus if (foo == 0){})

Have you got any other ideas why should I use it?

2条回答
We Are One
2楼-- · 2019-01-15 19:08

As you say, the reason some people use it is to occasionally avoid typing = when they mean ==.

Since it only catches some cases, where you're comparing a lvalue with a constant or rvalue, and every compiler I know of will warn you if you make that mistake, there's very little point in doing it.

At least to native English speakers, it makes the code read as if it's written backwards; so a "Yoda condition" some call it do. Like many rules in corporate style guides, it dates back to a time when dealing with unforgiving compilers was a higher priority than writing readable code.

查看更多
姐就是有狂的资本
3楼-- · 2019-01-15 19:20

Yes, you guessed it right. It's the good, old Yoda condition!!!

enter image description here

查看更多
登录 后发表回答