6.6. Types, Constants and Expressions

Use constants with the correct type [Constant type: 1-2 points]

  • Use 0 for an integer or real constant,

  • Use NULL for a pointer constant, not 0 or '\0'.

  • Use '\0' for a character constant, If you mean '0', write '0', not 48. If you mean '\n', write '\n', not 10. For example, if x is an integer from 0 to 9 then expression

      x + '0'
    
    yields the corresponding character (from '0' to '9'). Do not write
      x + 48
    
    It is much easier to read your program if your constants express what they really are.


Only use boolean operations on boolean values [Boolean op: 1-2 points]

Boolean operations (!, && and ||) should only be used on boolean values (which are known to be 0 or 1). Do not use them on integers, pointers, etc. (But see the exception in the next entry.)

Conditions should be boolean [Boolean condition: 1-2 points]

The condition in an if-statement, while-statement, for-statement, do-statement, or any other construct that performs a yes/no test should be a boolean value. It should not be a number or a pointer.

An exception is an expression that uses the ctype library, such as isdigit((unsigned) c) and isalpha((unsigned) c). Those can be used in tests as boolean values.


Do not use == true or == false [Boolean eq: 1-2 points]

An if-statement, while-statement, etc. tests whether its condition is true. Do not write something like
  if(isEmpty(x) == true)
where you redundantly ask if isEmpty(x) is true. Write
  if(isEmpty(x))
Use ! for negation. Instead of
  if(isEmpty(x) == false)
write
  if(!isEmpty(x))

Do not use if(x = y) [Assign in test: 1-3 points]

Even if it is what you intend to write, do not use an assignment as the test in an if, while, do or for statement. If you ask for warnings (which you always should), g++ will warn you about this.

Avoid long and complicated expressions [Complicated: 1-3 points]

Do not use long, complicated expressions that are difficult to read and understand. Do not make excessive use of ! in boolean expressions.