Trap 1 - Type Cast

◀ Can You Spot Bugs?▶ Trap 2 - cin.get()
Amazon Type cast refers to the way a variable of a type changes to another type implicitly or explicitly. As an exercise to see how much you know about type casting predict the output of the following program.
using namespace std;
int main() {
	double result;
	int numOfPies, numOfPeople;
	numOfPies = 14;
	numOfPeople = 3;
	result = numOfPies/numOfPeople;	
	cout<<numOfPies<<" pies split up evenly between "<<numOfPeople<<" people.\n";
cout<<"Therefore, each person gets "<<result<<" pies.\n"; return 0; }
Solution: The output looks like this:

14 pies split up evenly between 3 people.
Therefore, each person gets 4 pies
The intention of this program is to divide 14 pies evenly between 3 people, so each one should get 4 2/3 pies, but why does the output say each person gets only 4 pies?

First we check the type of result, which is double, so there should not be any problem. However, numOfPies and numOfPeople are int. The result of numOfPies/numOfPeople, therefore, is 4. Now because the types of both operands should match, 4 is transformed into double.

By examining this example, it is not hard to see that many bugs come from lack of understanding of the programming language. Therefore, the first step to improve your programming skills is to completely understand the programming language you are using.

Let’s look at the next exercise!
◀ Can You Spot Bugs?▶ Trap 2 - cin.get()

Questions? Let me know!