Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explicit type conversion (functional notation) with simple-type-specifier

Porting some code I have discovered that line

unsigned char uc = unsigned char(c);

is accepted by MSVC but rejected by GCC. Is this syntax correct?
Standard says that

A simple-type-specifier (7.1.7.2) ... followed by a parenthesized optional expressionlist or by a braced-init-list (the initializer) constructs a value of the specified type given the initializer

Does it mean that MS is right? Is unsigned char a 'simple-type-specifier'?

like image 856
AVK Avatar asked Aug 16 '16 14:08

AVK


People also ask

What is explicit type conversion?

Explicit type conversion, also called type casting, is a type conversion which is explicitly defined within a program (instead of being done automatically according to the rules of the language for implicit type conversion). It is defined by the user in the program.

What are the types of type conversion?

There are two types of conversion: implicit and explicit. The term for implicit type conversion is coercion. Explicit type conversion in some specific way is known as casting. Explicit type conversion can also be achieved with separately defined conversion routines such as an overloaded object constructor.

What is implicit conversion in C?

Implicit type conversion in C language is the conversion of one data type into another datatype by the compiler during the execution of the program. It is also called automatic type conversion.


1 Answers

GCC and CLANG are correct, the code is not valid.

Simple type specifier is single-word type name:

The simple type specifiers are

simple-type-specifier:
    nested-name-specifieropt type-name
    nested-name-specifier template simple-template-id
    nested-name-specifieropt template-name
    char
    char16_t
    char32_t
    wchar_t
    bool
    short
    int
    long
    signed
    unsigned
    float
    double
    void
    auto
    decltype-specifier

type-name:
    class-name
    enum-name
    typedef-name
    simple-template-id

decltype-specifier:
  decltype ( expression )
  decltype ( auto )

unsigned char is not a simple-type-specifier, it's a combination of simple-type-specifiers, as shown in Table 9 from standard.

Table [tab:simple.type.specifiers] summarizes the valid combinations of simple-type-specifiers and the types they specify.

Table 9 — simple-type-specifiers and the types they specify

Specifier(s)  Type
...
unsigned char     “unsigned char” 
...

Here's an explanation from cppreference.com:

2) The functional cast expression consists of a simple type specifier or a typedef specifier (in other words, a single-word type name: unsigned int(expression) or int*(expression) are not valid), followed by a single expression in parentheses.

like image 110
songyuanyao Avatar answered Oct 28 '22 16:10

songyuanyao