In this article, I give you programming tips that can improve your C++ code. I will cover use of parentheses, long expressions, modifying objects, and more. By the time I'm done, you will hopefully have learned a few ways to make your code faster as well as easier to understand and maintain.
C++ Programming Tips - Modifying Objects (Page 2 of 5 )
Increment and decrement operators (style)
Always use increment and decrement operators to reduce the length of your code. This also portrays you as a mature programmer.
So for example, you should write
i++ or ++i
i-- or --i
where i is a C++ variable.
Watch out for operator precedence on long expressions.
Function Usage Basics and Libraries
Controlling the evaluation of assert invocations
The default behavior of an assert invocation is to evaluate assertions. The macro NDEBUG must be undefined for the expression in an assert invocation to be evaluated. Through the use of the following preprocessor statement, the evaluation of subsequent assertions can be turned off.
In some cases, evaluation of assertions can be turned on again through the use of the following preprocessor statement:
This process works because the actions that an assert invocation performs are nested within a conditional evaluation directive that checks whether NDEBUG is defined. It is a good practice to include the definition of NDEBUG at the start of a program that is distributed to users.
Safe input type
Professional software normally extracts its input in character form. This input is then validated and converted to the desired form (e.g. int). This provides a safe way of extracting data. If you do not respect this, you may suffer from the following consequence: if an int is required and the user accidentally types in a non-digit, the program might terminate with an error message that the user does not understand.