Interview answers verified by specialists.

Find interview questions and answers on this website:

See right interview answers on 30 common job interview questions

When should a type cast be used?

There are two situations in which to use a type cast. The first use is to change the type of an operand to an arithmetic operation so that the operation will be performed properly. The variable f1 is set to the result of dividing the integer i by the integer
j. The result is 0, because integer division is used. The variable f2 is set to the result of dividing i by j as well. However, the (float) type cast causes i to be converted to a float. That in turn causes floating-point division to be used and gives the result 0.75.

#include <stdio.h>
    int i = 3;
    int j = 4;
    float f1 = i / j;
    float f2 = (float) i / j;
    printf("3 / 4 == %g or %g depending on the type used.\n", f1, f2);

The second case is to cast pointer types to and from void * in order to interface with functions that expect
or return void pointers. For example, the following line type casts the return value of the call to malloc()
to be a pointer to a foo structure.

struct foo      *p = (struct foo *) malloc(sizeof(struct foo));

Do you know that?

62% can increase their income since becoming a freelancer Next


Fast Payments
Payoneer sing up to get free