简体   繁体   English

分号终止的if语句是否是良好的编码习惯?

[英]Are semicolon-terminated if-statements good coding practice?

I am looping i, j, k and n. 我循环i,j,k和n。 I want a statement to execute except when k == j and n == k . 我希望执行一条语句,但当k == jn == k时除外。

If I use the code like this: 如果我使用这样的代码:

if (k != j && n != i)
      //statement

The statement will not execute in two cases: 该语句在两种情况下不会执行:

  1. When k != j when n == j. 当k!= j时,当n == j时。
  2. When k == j when n != j. 当k == j时,n!= j。 ( which is not what I need ) 这不是我所需要的

So I used a code like this: 所以我使用了这样的代码:

if (k == j && n == i)
    ;else
    //statement

By this code the statement will successfully execute except when k == j && n == i . 通过此代码,语句将成功执行,除非k == j && n == i

Is semicolon-terminated if-statements is a good way of coding in C++? 分号终止的if语句是C ++编码的好方法吗?

No it's not a good way of coding. 不,这不是编码的好方法。 The usual way is to use ! 通常的方法是使用! to invert the logic: 反转逻辑:

if(!(k==j && n==i))
    //statement

Or you could use De Morgan's Law to invert the logic: 或者,您可以使用De Morgan定律来反转逻辑:

if(k!=j || n!=i)
    //statement

Your problem is that you're negating the condition incorrectly. 您的问题是您错误地否定了条件。 You should just do: 您应该这样做:

if (!(k==j && n==i))
  // statement

Or, by De Morgan's laws: 或者,根据De Morgan的法律:

if (k != j || n != i)
  // statement

... is a good way of coding? ...是编码的好方法吗?

No. 没有。

You should write 你应该写

if (!(k == j && n == 1))
{
    //statement
}

Putting a semicolon after an if , for , or while is almost always wrong. ifforwhile之后放置分号几乎总是错误的。 It is highly unexpected and makes reading your code very difficult. 这是非常出乎意料的,并且使阅读代码非常困难。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM