Chaining Bool values give opposite result to expected

后端 未结 5 1909
忘掉有多难
忘掉有多难 2020-12-17 15:32

Unthinkingly I wrote some code to check that all the values of a struct were set to 0. To accomplish this I used:

bool IsValid() {
    return !(0 == year ==          


        
5条回答
  •  半阙折子戏
    2020-12-17 15:39

    Your error here is writing a mathematical expression using equals signs, and unthinkingly supposing that the computer will perform the test you meant - what a human mathematician would see as the meaning of those symbols. What the computer does (as per the definition of the language) is to perform a series of discrete comparisons, each of which returns true or false - and this true or false is then used in the next comparison. You aren't comparing all of those variables to 0, you're comparing each (bar two of them) to the result of comparing another two of the said variables.

提交回复
热议问题