Introduction to Programming and C++

Contents Previous Topic Next Topic

Casting in C is much more primitive than C++. You must prefix the variable you wish to cast with the type in parentheses, as shown in Program 1.

Program 1. Simple casting.

#include <stdio.h>

int main() {
	int n = 123456789;

	printf( "Printing as an integer: %d\n", n );

	/* Treat n as if it were a double. */
	printf( "Printing as a double: %lf\n", (double) n );

	return 0;
}

Unfortunately, the way in which casting is done, it can be difficult to determine what is being cast as what. Consider Program 2 which has the statement (double) m/n. At first glance, this may suggest that integer division is performed first and the result is cast as a double.

Program 2. Casting in an expression

#include <stdio.h>

int main() {
	int m = 23;
	int n = 7;

	printf( "The result of %d/%d is %lf\n", m, n, (double) m/n );

	return 0;
}

The casting operator (), however, actually has the highest possible precedence, and therefore, Program 2 would first treat m as a double, and when the compiler sees a double divided by an int, it promotes the int to a double. Program 3, however, is slightly clearer (and does not affect run-time).

If you just printed the characters with %c, the quotes would not appear.

Program 3. Clear example of casting.

#include <stdio.h>

int main() {
	int m = 5;
	int n = 7;

	printf( "The result of %d/%d is %lf\n",
		m, n, ((double) m)/((double) n) );

	return 0;
}

Program 3 clearly indicates that both the numerator and the denominator are being cast to doubles and the cast applies only to those variables.

Problems

Unfortunately, there are three other operators which have the same precedence as casting: [], ->, and .. In these cases, the compiler will often carefully examine your code, determine what it is you did not want, and then choose to compile that version. (That is, use parentheses to indicate exactly what it is you are casting.)


Questions

1. In Program 2, replace the 3rd additional argument to printf with (double) (m/n). What happens?


Contents Previous Topic Top Next Topic