-1

Either of below methods gives me the same value when I use it on a char type variable. So what are the differences between them?

  • (int)c
  • int{c}
  • static_cast<int>(c)
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • 1
    Did you read a good [C++ programming book](https://www.stroustrup.com/programming.html)? Did you read the C++11 draft standard [n3337](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3337.pdf)? Did you read the documentation of your C++ compiler, perhaps [GCC](http://gcc.gnu.org) ? Did you look into some [C++ reference website](https://en.cppreference.com/w/cpp) ? – Basile Starynkevitch Oct 06 '20 at 11:36
  • In practice, in most cases (with [GCC](http://gcc.gnu.org/) at least), the generated machine code would be *exactly* the same. Try playing with `g++ -fverbose-asm -O -S` then look into the generated assembler code – Basile Starynkevitch Oct 06 '20 at 11:46
  • gotta be a dupe, e.g. of [C++ cast syntax styles](https://stackoverflow.com/questions/32168/c-cast-syntax-styles) – underscore_d Oct 06 '20 at 11:54

1 Answers1

2

For starters using eth functional notation of casting requires s simple type specifier.

That is you may not for example write

unsigned int( c )

The functional notation of a casting creates a temporary object.

While using the explicit type conversion you may create for example an lvalue reference.

Here is a demonstrative program.

#include <iostream>

int main()
{
    char c = 'A';

    ++( char &)c;

    std::cout << "c = " << c << '\n';
}

From the C++ Standard (5.2.3 Explicit type conversion (functional notation)

3 Similarly, a simple-type-specifier or typename-specifier followed by a braced-init-list creates a temporary object of the specified type direct-list-initialized (8.5.4) with the specified braced-init-list, and its value is that temporary object as a prvalue.

As for static_cast then accoding to the C++ Standard (5.2.9 Static cast)

1 The result of the expression static_cast(v) is the result of converting the expression v to type T. If T is an lvalue reference type or an rvalue reference to function type, the result is an lvalue; if T is an rvalue reference to object type, the result is an xvalue; otherwise, the result is a prvalue. The static_cast operator shall not cast away constness

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335