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

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

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.

What are the names of type(myVar) and (type)myVar? Are they both bad practice?

Almost a rehash of What's the difference between function(myVar) and (function)myVar?
But I want to know:
What is the name of these variants and are they 'bad'?
type(myVar) is constructor like syntax, but for a basic type is it the same as doing a C-style cast which is considered bad in C++?
(type)myVar this one certainly does seem to be a C-style cast and thus must be bad practice?
I've seen some instances where people replace things like (int)a with int(a) citing that the C-style version is bad/wrong yet the linked question says they're both the same!
What is the name of these variants
type(expr) is known as a function-style cast.
(type)(expr) is known as a C-style cast.
and are they 'bad'?
Yes. First off, both are semantically completely equivalent. They are “bad” because they aren’t safe – they might be equivalent to a static_cast, but equally a reinterpret_cast, and without knowing both type and the type of expr it’s impossible to say1. They also disregard access specifiers in some cases (C-style casts allow casting inside a private inheritance hierarchy). Furthermore, they are not as verbose as the explicit C++ style casts, which is a bad thing since casts are usually meant to stand out in C++.
1 Consider int(x): Depending on x’ type, this is either a static_cast (e.g. auto x = 4.2f;) or a reinterpret_cast (e.g. auto x = nullptr; on an architecture where int is large enough to hold a pointer).

C++ casting for C-style downcasting

When working with a C API that uses C-style inheritance, (taking advantage of the standard layout of C-structs), such as GLib, we usually use C-style casts to downcast:
struct base_object
{
int x;
int y;
int z;
};
struct derived_object
{
base_object base;
int foo;
int bar;
};
void func(base_object* b)
{
derived_object* d = (derived_object*) b; /* Downcast */
}
But if we're writing new C++ code that uses a C-API like this, should we continue to use C-style casts, or should we prefer C++ casts? If the latter, what type of C++ casts should we use to emulate C downcasting?
At first, I thought reinterpret_cast would be suitable:
derived_object* d = reinterpret_cast<derived_object*>(b);
However, I'm always wary of reinterpret_cast because the C++ standard guarantees very little about what will happen. It may be safer to use static_cast to void*:
derived_object* d = static_cast<derived_object*>(static_cast<void*>(b))
Of course, this is really cumbersome, making me think it's better to just use C-style casts in this case.
So what is the best practice here?
If you look at the specification for C-style casts in the C++ spec you'll find that cast notation is defined in terms of the other type conversion operators (dynamic_cast, static_cast, reinterpret_cast, const_cast), and in this case reinterpret_cast is used.
Additionally, reinterpret_cast gives more guarantees than is indicated by the answer you link to. The one you care about is:
§ 9.2/20: A pointer to a standard-layout struct object, suitably converted using a reinterpret_cast, points to its initial member (or if that member is a bit-field, then to the unit in which it resides) and vice versa.
If you want to use a cast notation I think using the C++ type conversion operators explicitly is best. However rather than littering casts all over the code you should probably write a function for each conversion (implemented using reinterpret_cast) and then use that.
derived_object *downcast_to_derived(base_object *b) {
return reinterpret_cast<derived_object*>(b);
}
However, I'm always wary of reinterpret_cast because the C++ standard
guarantees very little about what will happen.
C++-style casts are no less safe than C-style casts, because C-style cast is defined in terms of C++-style casts.
5.4.4 The conversions performed by
— a const_cast (5.2.11),
— a static_cast (5.2.9),
— a static_cast followed by a const_cast,
— a reinterpret_cast (5.2.10), or
— a reinterpret_cast followed by a const_cast,
can be performed using the cast notation of explicit type conversion.
[...]
If a conversion can be interpreted in more than one of the ways listed above, the interpretation that
appears first in the list is used, even if a cast resulting from that interpretation is ill-formed.
The sad answer is that you can't avoid casts in code like you written, because the compiler knows very little about relations between classes. Some way or another, you may want to refactor it (casts or classes or the code that uses them).
The bottom line is:
If you can, use proper inheritance.
If you can't, use reinterpret_cast.
new C++ code that uses a C-API like this
Don't write new C++ code in a C style, it doesn't make use of the C++ language features, and it also forces the user of your wrapper to use this same "C" style. Instead, create a proper C++ class that wraps the C API interface details and hides them behind a C++ class.
should we continue to use C-style casts
No
or should we prefer C++ casts
Yes, but only when you have to.
Use C++ inheritance and virtual accessor functions (probably). Please show how you plan to use the derived object in func, this may provide a better answer for you.
If func expects to use the methods of the derived object, then it should receive a derived object. If it expects to use the methods of a base_object, but the methods are somehow changed because the pointer is to a derived_object, then virtual functions are the C++ way to do this.
Also, you want to pass a reference to func, not a pointer.
dynamic_cast, requires certain conditions to be met:
http://www.cplusplus.com/doc/tutorial/typecasting/
If you are just converting struct ptrs to struct ptrs and you know what you want, then static_cast, or reinterpret_cast may be the best?
However, if you truly are interested in writing C++ code, then the casts should be your last and final resort, since there are better patterns. The two common situations I would consider casting are:
You are interfacing with some event passing mechanism that passes a generic base class to an event handler.
You have a container of objects. The container requires it to contain homogenous types (i.e every element contains the same "thing"), but you want to store different types in the container.
I think dynamic_cast is exactly what you want.

C++ cast syntax

I've never seen the following cast syntax:
int var = int(1.0);
int is a base type so I'm wondering: is it equivalent to
int var = (int)1.0;
?
The two notations are equivalent(in the case of primitive types). Just a side note: please use static_cast in c++ instead of C-style casting. Does not make too much difference here but this is a bad habit.
For complex types first one would be calling a constructor while the second one is calling a casting operator and thus they may have quite different logic.
The first call is a constructor call.. The second is casting. They are basically the same.
Both solutions are syntactically correct and equivalent methods of explicit type casting.
http://www.cplusplus.com/doc/tutorial/typecasting/

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);