Skip to content
May 27, 2010 / raJkumar S

The usual but unusual arithmetic conversion.

Its been a year since one of my colleague encountered this usual but unusual arithmetic conversion. Just go through the below c++ code.

	    main(){
		 int a_variable = 2010;
		 if (true == a_variable ){
			cout<<"I think Microsoft named .Net so it wouldn’t show up in a Unix directory listing.";
		 }
	    }

Do you see the quote as output? If you think you will, continue reading.

The condition true == a_variable will be true only when a_variable is 1.
Stroustrup explains why the expression true == a_variables return true only when a_variable is ‘1’ by the rule “the usual arithmetic conversion”,the rule says the overall aim is to produce a result of the “largest operand type”: if a binary operator has a floating-point/long operand, all other operands are converted to floating-point/long and the operation is applied.
For any operands that are smaller than an int (say char, bool) is first converted in to an int before the operation is applied. So in our case true being a bool it is first converted to int i.e., 1 then compared with a_variable. So the expression return true only if and only if a_variable is 1.

But if you want true == a_variable true for all non zero values, do a explicit conversion of a_variable to bool i.e., bool(a_variable).

           main(){
			 int a_variable = 2010;
			 if (true == bool(a_variable) ){
				cout<<"I think Microsoft named .Net so it wouldn’t show up in a Unix directory listing.";
			 }
			}

Don’t get alarmed that c++ does things unexpected but pay attention to the compiler warnings.
warning C4805: ‘==’ : unsafe mix of type ‘bool’ and type ‘int’ in operation

Further reading
What the stackoverflow says about it
Integral Promotion

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: