Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unusual static_cast syntax

Tags:

c++

casting

I managed to track a bug down to the following expression:

foo(static_cast<T>(a, b)); // Executes specialisation 1

The closing bracket was in the wrong place. The correct statement should have been:

foo(static_cast<T>(a), b); // Executes specialisation 2

I've never seen static_cast used with the form (a,b), or seen it described anywhere. What does it mean? The former statement returned b.

like image 477
Robinson Avatar asked May 29 '15 14:05

Robinson


People also ask

What is the use of static_cast in C++?

The static_cast operator converts variable j to type float . This allows the compiler to generate a division with an answer of type float . All static_cast operators resolve at compile time and do not remove any const or volatile modifiers.

What does static_cast double do?

static_cast takes the value from an expression as input, and returns that value converted into the type specified by new_type (e.g. int, bool, char, double).

Is static_cast a function?

static_cast is actually an operator, not a function.

What is meant by static cast?

Static Cast: This is the simplest type of cast which can be used. It is a compile time cast.It does things like implicit conversions between types (such as int to float, or pointer to void*), and it can also call explicit conversion functions (or implicit ones).


2 Answers

static_cast is not a function, it's a keyword, so the comma in a, b is not an argument separator; it is the comma operator. It evaluates a but throws away the result. The expression evaluates to b.

like image 90
John Kugelman Avatar answered Nov 15 '22 08:11

John Kugelman


This has nothing to do with static_cast, but "makes use" of the comma operator. Its result is its right hand side, so

foo(static_cast<T>(a, b));

is equivalent to

foo(static_cast<T>(b));

unless a has other effects (which would then be executed and have their result discarded). With the right compiler settings, you will be warned about such things: Live

like image 36
Baum mit Augen Avatar answered Nov 15 '22 09:11

Baum mit Augen