I'm trying to compile this:
typedef struct Type {
int value;
} Type;
Type foobar(Type value) { return (Type)value; }
In MSVC2017, this throws the following error:
C2440: 'type cast': cannot convert from 'Type' to 'Type'
This doesn't seem to happen if the filename ends in .cpp as opposed to .c. This also doesn't seem to happen with gcc
. Why does this happen?
CodePudding user response:
(Type)value
violates the constraint in C 2018 6.5.4 2, which covers the cast operator:
Unless the type name specifies a void type, the type name shall specify atomic, qualified, or unqualified scalar type,…
A scalar type is an arithmetic or pointer type, per C 2018 6.2.5 21:
Arithmetic types and pointer types are collectively called scalar types. Array and structure types are collectively called aggregate types.
C has different rules and GCC, in its default mode, does not conform to the C standard in this respect.
There is no need for a cast here; in the return
statement, value
refers to the value
parameter of the function, which has type Type
. So return value;
would suffice.