Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a diference between ((int) a) and (int(a))?

What is a difference between ((int) a) and (int(a))?

Is the second expression valid in pure "С" (not "C" under "C++")?

like image 987
NoSkill Avatar asked Jan 19 '20 09:01

NoSkill


2 Answers

There's no difference between them in C++. However, C supports only the first cast operation.

See this example from tutorial:

double x = 10.3;
int y;
y = (int) x;    // c-like cast notation 
y = int (x);    // functional notation
like image 137
Mohammed Deifallah Avatar answered Nov 08 '22 17:11

Mohammed Deifallah


(type_name)identifier (or more specifically (type_name)cast_expression (6.5.4)) is a C-style cast. (int(a)) is syntactically invalid in C unless a is a type. Then it could be part of a cast to a function taking type a and returning int, which would be a syntactically valid but semantically invalid cast, so useless too. int(a); in C would be a declaration equivalent to int a;.

C++ does support the int(a) syntax for casts (the type name must be a single word; it doesn't work with e.g., unsigned long(a)) on the grounds that int (the type name) then becomes kind of like a type with a parametrized constructor (although even this is in C++ grouped together with C-style casts as a kind of a deprecated way of casting, and the more fine-grained/visible static_cast/reinterpret_cast/const_cast casts are preferred).

The C++ syntax then appears to be quite interesting because this works (C++):

typedef int type_name;
type_name (a); //a declaration
a=0;
printf("%d\n", type_name(a)); //type_name(a) is a cast expr here
like image 43
PSkocik Avatar answered Nov 08 '22 18:11

PSkocik