M.S Chaudhari M.S Chaudhari - 4 months ago 23
C Question

Explicit type casting operator in C/C++

The following code converts the float type

to an integer value
, the remainder is lost. Here, the typecasting operator is
. I know it is valid typecast in C++.

int main()
int i;
float f = 7.5;
i = (int) f; // Valid in C/C++

But another way to do the same thing in
is to use the functional notation preceding the expression to be converted by the type and enclosing the expression between parentheses:

i = int (f); // It is worked in C++ but not C

So, I have a question, Is it valid way to typecast in C++?

i = int (f);

is valid in C++ but not in C.

From the C99 Standard, 6.5.4 Cast operators

      ( type-name ) cast-expression

C++ supports the above form of casting as well as function style casting. Function style casting is like calling the constructor of a type to construct on object.

Check out the following block code compiled using C and C++.

#include <stdio.h>

int main()
   float f = 10.2;
   int i = int(f);

   printf("i: %d\n", i);

Non-working C program: http://ideone.com/FfNR5r

Working C++ program: http://ideone.com/bSP7sL