Trap 3 - Another Type Cast
◀ Trap 2 - cin.get()▶ Trap 4 - Decimal Number Amazon
Type casting can be tricky. Sometimes when a variable is cast to a different type it gives you results you don’t anticipate. Predict the output of executing the following program.
#include<iostream>
using namespace std;
#include<string>
int buggy(string s){
int counter=-1;
while(counter<s.length())
counter++;
return counter;
}
int main(){
string s = “Charlotte and Marlene are angels.”;
cout<<buggy(s)<<endl;
return 0;
}
Solution
To our surprise, the output is –1, not the length of s! However, if you change the initial value of counter from –1 to 0, the output will be 33. In fact, the result of evaluating counter<s.length() is false, even though s.length() is 33. If you do,
int ti=s.length();
cout<<(counter<ti)<<endl;
You will get “true”. So what is going on here?
The problem is that s.length() returns an unsigned integer. When compared with an unsigned integer, the integer gets promoted to be unsigned, turning -1 into a huge positive number. When you store the value of s.length() into an integer variable and then do the comparison of integer and integer, then you get expected results.
You should be able to figure out the rest; if not refer to
Chapter 16.4.
Next let’s look at the decimal number trap!
◀ Trap 2 - cin.get()▶ Trap 4 - Decimal Number