Submitted by tushar pramanick on Tue, 03/05/2013 - 16:10

Playing with the Cast Operator

In C, you can convert one data type to a different one by prefixing the cast operator to the operand.

The general form of the cast operator is

(data-type)x

Here data-type specifies the data type you want to convert to. x is a variable (or, expression) that contains the value of the current data type. You have to include the parentheses ( and ) to make up a cast operator.

For example, the (float)5 expression converts the integer 5 to a floating-point number, 5.0.

The program in Listing 6.4 shows another example of using the cast operator.
TYPE
Listing 6.4. Using the cast operator.

1:  /* 06L04.c: Using the cast operator */
2:  #include <stdio.h>
3:
4:  main()
5:  {
6:     int x, y;
7:
8:     x = 7;
9:     y = 5;
10:    printf("Given x = %d, y = %d\n", x, y);
11:    printf("x / y produces: %d\n",  x / y);
12:    printf("(float)x / y produces: %f\n",  (float)x / y);
13:    return 0;
14: }

    OUTPUT
    The following output is obtained by running the executable 06L04.exe from a DOS prompt:

    C:\app> 06L04
    Given x = 7, y = 5
    x / y produces: 1
    (float)x / y produces: 1.400000
    C:\app>

    ANALYSIS
    In Listing 6.4, there are two integer variables, x and y, declared in line 6, and initialized in lines 8 and 9, respectively. Line 10 then displays the values contained by the integer variables x and y.

The statement in line 11 prints out the integer division of x/y. Because the fractional part is truncated, the result of the integer division is 1.

However, in line 12, the cast operator (float) converts the value of x to a floating-point value. Therefore, the (float)x/y expression becomes a floating-point division that returns a floating-point number. That's why you see the floating-point number 1.400000 shown on the screen after the statement in line 12 is executed.

Related Items

Manipulating Bits

Manipulating Bits

In previous hours, you learned that computer data and files are made of bits (or bytes). There is even an operator in C_the sizeof operator_that can be used to measure the number of bytes for data types.

Everything Is Logical

Everything Is Logical

Now, it's time for you to learn about a new set of operators: logical operators.

There are three logical operators in the C language:
&&     The logical AND operator
||     The logical OR operator

Question and Answer

    Q Why do we need the sizeof operator?

Exercises : Answer the following Question

To help solidify your understanding of this hour's lesson, you are encouraged to answer the quiz questions and finish the exercises provided in the Workshop before you move to the next lesson.

Playing with an Infinite Loop

Playing with an Infinite Loop

If you have a for statement like this,

for ( ; ; ){
  /* statement block */
}