if, else combinations

  if, else looks very simple, but also to learn the most when we get started logical structure, but after reading the C language in-depth analysis, have a new understanding. Following a few simple questions about the record.

  1.bool variables were compared with the "zero value"

  bool bTestFlag = FALSE;

  //写法A
  if(bTestFlag == 0);
  if(bTestDlag == 1);

  //写法B
  if(bTestFlaf == TRUE);
  if(bTestFlag == FALSE);

  //写法C
  if(bTestFlag);
  if(!bTestFlag);

  Above that is the correct wording of it? A first look at the wording, it is easy to mistakenly believe that the wording A bTestFlag is an integer variable, so such an approach is not good. Look at the wording B, we all know the value FALSE (the compiler is defined as 0), but be aware that not all of the value of TRUE 1, such as Visual Basic took TRUE defined as -1, so such an approach also not good. Finally, take a look at the wording of C, if the statement is an expression of its value against the rear brackets to branch jump, if the expression is true if the statement immediately following the code is executed; otherwise it is not executed. C so well written, does not cause misunderstanding, the definition is not due to different values ​​TRUE or FALSE and error. So after writing code is noteworthy, written by C method is better.

  2.float variables and "zero value" to compare

  float fTestVal = 0.0;

  A written //

  if(fTestVal == 0.0);        if(fTestVal != 0.0);

  // writing B

  if((fTestVal>=-EPSINON)&&(fTestVal<=EPSINON));

  Accuracy is defined EPSINON

  Above wording is correct it? We know that there are float and double precision limits, certainly not directly used with the correct ratio of 0.0. EPSINON accuracy is defined, if a chatter in the [0.0-EPSINON, 0.0 + EPSINON] within the closed interval, we consider that it is equal to the value of zero value within a certain accuracy.

  3. The pointer variables and "zero value" is compared

  int * p = NULL;

  (A) if(p == 0);

  (B) if(p);

  (C)if(NULL == p);

  Those above wording is correct? analyse as below:

  In writing A, easily mistaken p is an integer variable, causing misunderstanding, even though NULL value and 0 the same, but different in meaning, so this is not good writing.

  In writing B, easily mistaken p is bool type variable, not good.

  C final wording is correct.

  4. A number of issues need to pay attention if statement

  •   Normally processed first, and then deal with the abnormal situation
  • And to ensure that if there is no else clause backwards
  • Assignment operator can not be used in a boolean expression to generate
  • All of the if-else if the structure should be ended by the else clause

 

Guess you like

Origin www.cnblogs.com/taoye1997/p/11884578.html