Identifying 3 common programming mistakes

Here is a list of common subtle coding mistakes which are not always detected by your compiler (the code may compile without any compiler errors) and which can easily hide in your code for a while…

Note that all these bugs can be found by monitoring variables, values, and code execution, as presented previously.


1) Using incorrect data type

If you assign a value to a variable and you realize that the real value hold by this variable is totally different from what you asked, then this is because the data type of your variable (boolean, char, integer…) is not adapted to this value.

For instance, Integers can only hold values between -32767 and 32768. If you try to assign 50000 to an Integer, it will actually hold -15536 which is not at all the desired value.

So how do you select the correct data type? The idea is to select the data type that use the less memory as possible, that is, the smaller number of bytes as possible. In our example with 50000, we have 2 options:

  1. To use the Unsigned version of the selected type, that is Unsigned Integer which hold values between 0 and 65535. This option is ideal if you don’t need to use negative numbers.
  2. To select the next bigger data type, which is Long.


2) Using the wrong operator (=, ==)

Use of the “assignment” operator (=) instead of the “equal to” operator (==), and vice versa, are very frequent mistakes. These are usually errors of inattention.

Example 1

Instead of using:

if(myVar == 2)

You might erroneously use:

if(myVar = 2)

So, instead of testing if myVar is equal to 2, we are assigning the value 2 to myVar. The value of myVar is then tested by the IF statement. As it is different from 0, the condition is true (the condition is false only if this value is equal to 0).

Example 2

Instead of using:

myVar = 2;

You might erroneously use:

myVar == 2;

Thus, instead of assigning the value 2 to myVar, we are testing if myVar is equal to 2. And the result of the test (true or false) is returned but is unused.


3) Expecting float from non-float divisions

The last most common mistakes that you could do is to perform a division on non-float numbers and expect a float value as a result.


Let’s say you want to calculate the result of the division of 9 by 2:

float result = 9/2; // result = 4

As 5 and 2 are both considered as Integers by the compiler, the result of the division will be an Integer, so 4. To ask the compiler to perform a float division, do either of these 2:

  • Add a decimal to all the numbers
float result = 9.0/2.0; // result = 4.5
  • Cast all numbers as float
float result = (float) 9 / (float) 2; // result = 4.5


Was this article helpful?
0 out of 0 found this helpful