Changing/punning types [duplicate] - c++

This question already has answers here:
C++ cast syntax styles
(10 answers)
What's the difference between type(myVar) and (type)myVar?
(2 answers)
What is the difference between (type)value and type(value)?
(5 answers)
Closed 3 years ago.
Consider:
b = (int) a; // C-like cast notation
b = int (a); // Functional notation

Apparently I was wrong in my initial cut at an answer. They are roughly equivalent. And while compound type names like long long or void * can't use functional syntax directly (i.e. long long(val) doesn't work), using typedef can get around this issue.
Both cast notations are very bad and should be avoided. For example:
const char c = 'a';
void *fred = (void *)(&c);
works, and it shouldn't.
Both the C-style cast notation will sometimes behave like static_cast, sometimes like const_cast, sometimes like reinterpret_cast, or even a combination of the two depending on the exact situation in which it's used. These semantics are rather complex and it's not always easy to tell exactly what's happening in any given situation.
I have gone to using mostly C++ static_cast<type>(val) style casts, and never use C-style casts. Based on my research for this question I'm going to also stop using function-style casts for anything. The question "C++ cast syntax styles" has an excellent answer (the accepted one) that details why.

There's hardly any difference. Officially, the first tells the compiler that the value is an integer. This probably doesn't generate any extra code at all. The function call is an actual call that internally performs the other typecast. A smart compiler will optimize this, so they are actually the same.

There isn't any difference. It is a matter of preference. These are old-style casts.

It depends where you use it and how. I.e. if you have values or pointers (or pointers of pointers).
With C++ you should read up on *_cast<> and use them instead.

Related

Why should I use 'static_cast' for numeric casts in C++?

Sometimes, we need to explicitly cast one numeric type to another (e.g. to avoid warning when we lose precision or range). For some:
double foo;
we could write:
(float)foo
but most C++ programmers say it's evil 'old-style cast' and you should use the 'new-style cast':
static_cast<float>(foo)
There is an alternative of boost::numeric_cast which is quite interesting (at least in not-performance-critical code) but this question is about static_cast.
A similar question was already asked, but the most important arguments used there are not valid for numerical cast (in my opinion, am I wrong?). There are they:
You have to explicitly tell the compiler what you want to do. Is it upcast, or downcast? Maybe reinterpret cast?
No. It is simple numeric cast. There is no ambiguity. If I know how static_cast<float> works, I know how does it work for 'old-style' cast.
When you write (T)foo you don't know what T is!
I'm not writting (T)foo but (float)foo. I know what is float.
Are there any important reasons for using a new, better casts for numeric types?
In a general scenario (which you have mentioned) you'd want explicit C++ cast to avoid possible issues mentioned in When should static_cast, dynamic_cast, const_cast and reinterpret_cast be used? (ability to devolve into reinterpret_cast).
In numeric scenario you get two benefits at least:
you don't need to remember that C-style cast for numerics safely devolves to static_cast and never reaches reinterpret_cast - I'd call it "ease of use" and "no surprises" part
you can textually search for cast operations (grep 'static_cast<double>' vs grep '(double)' which can be part of function signature)
Like many things inherited from C, the more specific C++ variants are there to inform readers of the code, not the compiler.
You use static_cast<double> because it doesn't do all the things that (double) can.
The conversions performed by
a const_­cast,
a static_­cast,
a static_­cast followed by a const_­cast,
a reinterpret_­cast, or
a reinterpret_­cast followed by a const_­cast,
can be performed using the cast notation of explicit type conversion.
[expr.cast/4]
Specifying static_cast alerts you with a compile time error, rather than silently having undefined behaviour, if the expression you think is safe isn't.

NULL vs nullptr (Why was it replaced?) [duplicate]

This question already has answers here:
What exactly is nullptr?
(14 answers)
Closed 9 years ago.
I know that in C++ 0x or NULL was replaced by nullptr in pointer-based applications. I'm just curious of the exact reason why they made this replacement?
In what scenario is using nullptr over NULL beneficial when dealing with pointers?
nullptr has type std::nullptr_t. It's implicitly convertible to any pointer type. Thus, it'll match std::nullptr_t or pointer types in overload resolution, but not other types such as int.
0 (aka. C's NULL bridged over into C++) could cause ambiguity in overloaded function resolution, among other things:
f(int);
f(foo *);
(Thanks to Caleth pointing this out in the comments.)
You can find a good explanation of why it was replaced by reading A name for the null pointer: nullptr, to quote the paper:
This problem falls into the following categories:
Improve support for library building, by providing a way for users to write less ambiguous code, so that over time library writers will not need to worry about overloading on integral and pointer types.
Improve support for generic programming, by making it easier to express both integer 0 and nullptr unambiguously.
Make C++ easier to teach and learn.
Here is Bjarne Stroustrup's wordings,
In C++, the definition of NULL is 0, so there is only an aesthetic difference. I prefer to avoid macros, so I use 0. Another problem with NULL is that people sometimes mistakenly believe that it is different from 0 and/or not an integer. In pre-standard code, NULL was/is sometimes defined to something unsuitable and therefore had/has to be avoided. That's less common these days.
If you have to name the null pointer, call it nullptr; that's what
it's called in C++11. Then, "nullptr" will be a keyword.
One reason: the literal 0 has a bad tendency to acquire the type int, e.g. in perfect argument forwarding or more in general as argument with templated type.
Another reason: readability and clarity of code.

Difference between static_cast<primitive_type>(foo) and primitive_type(foo) [duplicate]

I've heard that the static_cast function should be preferred to C-style or simple function-style casting. Is this true? Why?
The main reason is that classic C casts make no distinction between what we call static_cast<>(), reinterpret_cast<>(), const_cast<>(), and dynamic_cast<>(). These four things are completely different.
A static_cast<>() is usually safe. There is a valid conversion in the language, or an appropriate constructor that makes it possible. The only time it's a bit risky is when you cast down to an inherited class; you must make sure that the object is actually the descendant that you claim it is, by means external to the language (like a flag in the object). A dynamic_cast<>() is safe as long as the result is checked (pointer) or a possible exception is taken into account (reference).
A reinterpret_cast<>() (or a const_cast<>()) on the other hand is always dangerous. You tell the compiler: "trust me: I know this doesn't look like a foo (this looks as if it isn't mutable), but it is".
The first problem is that it's almost impossible to tell which one will occur in a C-style cast without looking at large and disperse pieces of code and knowing all the rules.
Let's assume these:
class CDerivedClass : public CMyBase {...};
class CMyOtherStuff {...} ;
CMyBase *pSomething; // filled somewhere
Now, these two are compiled the same way:
CDerivedClass *pMyObject;
pMyObject = static_cast<CDerivedClass*>(pSomething); // Safe; as long as we checked
pMyObject = (CDerivedClass*)(pSomething); // Same as static_cast<>
// Safe; as long as we checked
// but harder to read
However, let's see this almost identical code:
CMyOtherStuff *pOther;
pOther = static_cast<CMyOtherStuff*>(pSomething); // Compiler error: Can't convert
pOther = (CMyOtherStuff*)(pSomething); // No compiler error.
// Same as reinterpret_cast<>
// and it's wrong!!!
As you can see, there is no easy way to distinguish between the two situations without knowing a lot about all the classes involved.
The second problem is that the C-style casts are too hard to locate. In complex expressions it can be very hard to see C-style casts. It is virtually impossible to write an automated tool that needs to locate C-style casts (for example a search tool) without a full blown C++ compiler front-end. On the other hand, it's easy to search for "static_cast<" or "reinterpret_cast<".
pOther = reinterpret_cast<CMyOtherStuff*>(pSomething);
// No compiler error.
// but the presence of a reinterpret_cast<> is
// like a Siren with Red Flashing Lights in your code.
// The mere typing of it should cause you to feel VERY uncomfortable.
That means that, not only are C-style casts more dangerous, but it's a lot harder to find them all to make sure that they are correct.
One pragmatic tip: you can search easily for the static_cast keyword in your source code if you plan to tidy up the project.
In short:
static_cast<>() gives you a compile time checking ability, C-Style
cast doesn't.
static_cast<>() can be spotted easily
anywhere inside a C++ source code; in contrast, C_Style cast is harder to spot.
Intentions are conveyed much better using C++ casts.
More Explanation:
The static cast performs conversions between compatible types. It
is similar to the C-style cast, but is more restrictive. For example,
the C-style cast would allow an integer pointer to point to a char.
char c = 10; // 1 byte
int *p = (int*)&c; // 4 bytes
Since this results in a 4-byte pointer pointing to 1 byte of allocated
memory, writing to this pointer will either cause a run-time error or
will overwrite some adjacent memory.
*p = 5; // run-time error: stack corruption
In contrast to the C-style cast, the static cast will allow the
compiler to check that the pointer and pointee data types are
compatible, which allows the programmer to catch this incorrect
pointer assignment during compilation.
int *q = static_cast<int*>(&c); // compile-time error
Read more on:
What is the difference between static_cast<> and C style casting
and
Regular cast vs. static_cast vs. dynamic_cast
The question is bigger than just using whether static_cast<> or C-style casting because there are different things that happen when using C-style casts. The C++ casting operators are intended to make those different operations more explicit.
On the surface static_cast<> and C-style casts appear to be the same thing, for example when casting one value to another:
int i;
double d = (double)i; //C-style cast
double d2 = static_cast<double>( i ); //C++ cast
Both of those cast the integer value to a double. However when working with pointers things get more complicated. Some examples:
class A {};
class B : public A {};
A* a = new B;
B* b = (B*)a; //(1) what is this supposed to do?
char* c = (char*)new int( 5 ); //(2) that weird?
char* c1 = static_cast<char*>( new int( 5 ) ); //(3) compile time error
In this example (1) may be OK because the object pointed to by A is really an instance of B. But what if you don't know at that point in code what a actually points to?
(2) may be perfectly legal (you only want to look at one byte of the integer), but it could also be a mistake in which case an error would be nice, like (3).
The C++ casting operators are intended to expose these issues in the code by providing compile-time or run-time errors when possible.
So, for strict "value casting" you can use static_cast<>. If you want run-time polymorphic casting of pointers use dynamic_cast<>. If you really want to forget about types, you can use reintrepret_cast<>. And to just throw const out the window there is const_cast<>.
They just make the code more explicit so that it looks like you know what you were doing.
static_cast means that you can't accidentally const_cast or reinterpret_cast, which is a good thing.
Allows casts to be found easily in
your code using grep or similar
tools.
Makes it explicit what kind
of cast you are doing, and engaging
the compiler's help in enforcing it.
If you only want to cast away
const-ness, then you can use
const_cast, which will not allow you
to do other types of conversions.
Casts are inherently ugly -- you as
a programmer are overruling how the
compiler would ordinarily treat your
code. You are saying to the
compiler, "I know better than you."
That being the case, it makes sense
that performing a cast should be a
moderately painful thing to do, and
that they should stick out in your
code, since they are a likely source
of problems.
See Effective C++ Introduction
It's about how much type-safety you want to impose.
When you write (bar) foo (which is equivalent to reinterpret_cast<bar> foo if you haven't provided a type conversion operator) you are telling the compiler to ignore type safety, and just do as it's told.
When you write static_cast<bar> foo you are asking the compiler to at least check that the type conversion makes sense and, for integral types, to insert some conversion code.
EDIT 2014-02-26
I wrote this answer more than 5 years ago, and I got it wrong. (See comments.) But it still gets upvotes!
C Style casts are easy to miss in a block of code. C++ style casts are not only better practice; they offer a much greater degree of flexibility.
reinterpret_cast allows integral to pointer type conversions, however can be unsafe if misused.
static_cast offers good conversion for numeric types e.g. from as enums to ints or ints to floats or any data types you are confident of type. It does not perform any run time checks.
dynamic_cast on the other hand will perform these checks flagging any ambiguous assignments or conversions. It only works on pointers and references and incurs an overhead.
There are a couple of others but these are the main ones you will come across.
static_cast, aside from manipulating pointers to classes, can also be used to perform conversions explicitly defined in classes, as well as to perform standard conversions between fundamental types:
double d = 3.14159265;
int i = static_cast<int>(d);

In C++, what are the differences between static_cast<double>(a) and double(a)?

What are the differences between
int a;
// a gets some value
double pi = static_cast<double>(a)/3;
and
int a;
// a gets some value
double pi = double(a)/3;
Have you ever seen the latter? It seems to me I saw it in some snippet written by Stroustrup but I can't find the reference.
Someone may have thought they were constructing rather than casting. Consider:
some_fun(std::string("Hello"));
Many people think they're calling a constructor there when in fact they're doing a C-style cast. It just so happens that casting will look at constructors of the target type among the long list of other things it looks at and so here it eventually ends up invoking the constructor.
Functional notation casts have all the same weaknesses of the other kind of C cast:
Can inadvertently cast away constness
Can silently turn into a reinterpret cast
Are hard to differentiate with grepping tools.
Besides all that though, you're performing exactly the same operation in both cases.
The latter is referred to as the functional notation of explicit casting where you explicitly say a should be treated as a double. You can pretty much cast anything to any type using this technique.
The former is the preferred way to cast a type in C++. It does basic checking to see that the type you are casting to makes sense (child class pointer to a base class pointer, etc.). In addition, like in the example you show, you can perform implicit conversions. Technically the static_cast in your example is explicit, but the result of the operation (the assignment) is implicit.
There is no difference in terms of generated assembly code between static_cast<double> (a) and (double) a. The key advantage of cast notation, (type_id) cast_expression, is that it is more flexible. In one situation it might be the equivalent of a const_cast, in another, a static_cast, in yet another, a dynamic_cast, in yet another, a combination of const_cast and static_cast (or dynamic_cast).
This strength is also a weakness. Cast notation means different things in different places. Another disadvantage is that it is very easy to find xxx_cast<type_id> (cast_expression). Just search for _cast. It is very hard to find expressions that use cast notation.
using static_cast is a safe C++-style way, but (double) - unsafe old C-style way.
see here: Type Casting
int a;
//This is the old way of converting a variable from its type to a double
double pi = double(a)/3;
//This is the new way of converting a variable from its type to a double
double pi = static_cast<double>(a)/3;
From Walter Savitch's book, (Problem Solving with CPP, 10th Edition) page 222

(int) ch vs. int(ch): Are they different syntaxes for the same thing?

In C++, is (int) ch equivalent to int(ch).
If not, what's the difference?
They are the same thing, and also the same as (int)(ch). In C++, it's generally preferred to use a named cast to clarify your intentions:
Use static_cast to cast between primitive types of different sizes or signednesses, e.g. static_cast<char>(anInteger).
Use dynamic_cast to downcast a base class to a derived class (polymorphic types only), e.g. dynamic_cast<Derived *>(aBasePtr).
Use reinterpret_cast to cast between pointers of different types or between a pointer and an integer, e.g. reinterpret_cast<uintptr_t>(somePtr).
Use const_cast to remove the const or volatile qualifiers from variables (VERY DANGEROUS), e.g. const_cast<char *>(aConstantPointer).
int(x) is called function-style cast by the standard and is the same as the C-style cast in every regard (for POD) [5.2.3]:
If the expression list is a single expression, the type conversion expression is equivalent (in definedness, and if defined in meaning) to the corresponding cast expression (5.4).
They are the same.
Konrad Rudolph is right. But consider that
(int) x <-- is valid syntax in C and C++
(int*) x <-- is valid syntax in C and C++
int (x) <-- is valid in C++, but gives a syntax error in C
int* (x) <-- gives a syntax error in both C and C++
Although the two syntaxes have the same meaning for int, the second, constructor-style syntax is more general because it can be used with other types in templates. That is, "T(x)" can be compiled into a conversion between primitive types (e.g., if T = int) or into a constructor call (if T is a class type). An example from my own experience where this was useful was when I switched from using native types for intermediate results of calculations to arbitrary-precision integers, which are implemented as a class.
The first is the C style, while the second is the C++ style.
In C++, use the C++ style.
It's worth noting that both styles of casting are deprecated in C++, in favor of the longer, more specific casting methods listed in Adam Rosenfield's answer.
If you want to be super-nasty, then if you write something like:
#define int(x) 1
Then (int)x has the meaning you expect, while int(x) will be 1 for any value of x. However, if anyone ever did this, you should probably hurt them. I can also quite believe that somewhere in the standard you are forbidden from #defining keywords, although I can't find it right now.
Except for that, very stupid, special case, then as said before, [5.3.2] says they are the same for PODs