M.S Chaudhari M.S Chaudhari - 1 year ago 121
C Question

Explicit type casting operator in C/C++

The following code converts the float type

7.5
to an integer value
7
, the remainder is lost. Here, the typecasting operator is
int
. 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
C/C++
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++?

Answer Source
i = int (f);

is valid in C++ but not in C.

From the C99 Standard, 6.5.4 Cast operators

 cast-expression:
      unary-expression
      ( 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