Explicit type casting operator in C/C++

回眸只為那壹抹淺笑 提交于 2019-12-23 06:43:48

问题


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++?


回答1:


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




回答2:


It is in C++. But although it is valid, C++ (opposed to C) encourages explicitness in your casting:

auto i = static_cast<int>(7.0);

(Oh, and use the type safe streams instead of the error-prone printf:

std::cout << i << "\n";


来源:https://stackoverflow.com/questions/39888189/explicit-type-casting-operator-in-c-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!