Is there a "safe" alternative to static_cast in C++11/14 or a library which implements this functionality?
By "safe" I mean the cast should only allow casts which do not lose precision. So a cast from int64_t to int32_t would only be allowed if the number fits into a int32_t and else an error is reported.
There's gsl::narrow
narrow // narrow<T>(x) is static_cast<T>(x) if static_cast<T>(x) == x or it throws narrowing_error
You've got the use-case reversed.
The intended use of static_cast (and the other c++-style casts) is to indicate programmer intentions. When you write auto value = static_cast<int32_t>(value_64);, you're saying "Yes, I very much *intend* to downcast this value, possibly truncating it, when I perform this assignment". As a result, a compiler, which might have been inclined to complain about this conversion under normal circumstances (like if you'd have written int32_t value = value_64;) instead observes "well, the programmer has told me that this is what they intended; why would they lie to me?" and will silently compile the code.
If you want your C++ code to warn or throw an error on unsafe conversions, you need to explicitly not use static_cast, const_cast, reinterpret_cast, and let the compiler do its job. Compilers have flags that change how warnings are treated (downcasting int64_t to int32_t usually only results in a Warning), so make sure you're using the correct flags to force warnings to be treated as errors.
Assuming the question is about compile-time detection of potentially lossy conversions...
A simple tool not mentioned yet here is that list initialization doesn't allow narrowing, so you can write:
void g(int64_t n)
{
int32_t x{n}; // error, narrowing
int32_t g;
g = {n}; // error, narrowing
}
NB. Some compilers in their default mode might show "warning" and continue compilation for this ill-formed code, usually you can configure this behaviour via compilation flags.
You can create your own with sfinae. Here's an example:
template <typename T, typename U>
typename std::enable_if<sizeof(T) >= sizeof(U),T>::type
safe_static_cast(U&& val)
{
return static_cast<T>(val);
}
int main()
{
int32_t y = 2;
std::cout << safe_static_cast<int32_t>(y) << std::endl;
std::cout << safe_static_cast<int16_t>(y) << std::endl; // compile error
}
This will compile only if the size you cast to is >= the source size.
Try it here
You can complicate this further using numeric_limits for other types and type_traits.
Notice that my solution is a compile-time solution, because you asked about static_cast, where static here refers to "determined at compile-time".
Related
As far as I know, std::to_integer<T> is equivalent to T(value) where value is a variable having type std::byte.
I looked into some implementations from the major compilers and found that in this case equivalent means literally implemented as. In other terms, most of the times to_integer is actually implemented as:
return T(value);
And that's all.
What I don't understand is what's the purpose of such a function?
Ironically the cons are even more than the pros. I should include a whole header for such a function just to avoid a C-like cast that is most likely directly inlined anyway.
Is there any other reason for that or it's just really a nice looking alternative for a C-like cast and nothing more?
it's just really a nice looking alternative for a C-like cast and nothing more?
You say that as though it's some trivial detail.
Casts are dangerous. It's easy to cast something to the wrong type, and often compilers won't stop you from doing exactly that. Furthermore, because std::byte is not an integral type in C++, working with numerical byte values often requires a quantity of casting. Having a function that explicitly converts to integers makes for a safer user experience.
For example, float(some_byte) is perfectly legal, while to_integer<float>(some_byte) is explicitly forbidden. to_integer<T> requires that T is an integral type.
to_integer is a safer alternative.
I should include a whole header for such a function
If by "whole header", you mean the same header you got std::byte from and therefore is already by definition included...
std::to_integer<T>(some_byte) is equivalent to T(some_byte) if it actually compiles. T(some_byte) is equivalent to the unsafe C-style cast of (T)some_byte, which can do scary things. On the other hand, std::to_integer is appropriately constrained to only work when it is safe:
This overload only participates in overload resolution if std::is_integral_v<IntegerType> is true.
If the T was not actually an integer type, rather than potentially having undefined behavior, the code won't compile. If the some_byte was not actually a std::byte, rather than potentially having undefined behavior, the code won't compile.
Beyond the expression of intent and safety issues already mentioned, I get the idea from the committee discussion on the paper that it’s meant to be like std::to_string and might have more overloads in the future.
A C style cast is not equivalent to std::to_integer<T>. See the below example.
std::to_integer<T> only participates in overload resolution if std::is_integral_v<T> is true.
#include <cstddef>
#include <iostream>
template <typename T>
auto only_return_int_type_foo(std::byte& b)
{
return std::to_integer<T>(b);
}
template <typename T>
auto only_return_int_type_bar(std::byte& b)
{
return T(b);
}
int main()
{
std::byte test{64};
// compiles
std::cout << only_return_int_type_foo<int>(test) << std::endl;
// compiler error
std::cout << only_return_int_type_foo<float>(test) << std::endl;
// compiles
std::cout << only_return_int_type_bar<int>(test) << std::endl;
// compiles
std::cout << only_return_int_type_bar<float>(test) << std::endl;
}
Consider the following piece of code:
struct foo {
static constexpr const void* ptr = reinterpret_cast<const void*>(0x1);
};
auto main() -> int {
return 0;
}
The above example compiles fine in g++ v4.9 (Live Demo), while it fails to compile in clang v3.4 (Live Demo) and generates the following error:
error: constexpr variable 'ptr' must be initialized by a constant expression
Questions:
Which of the two compilers is right according to the standard?
What's the proper way of declaring an expression of such kind?
TL;DR
clang is correct, this is known gcc bug. You can either use intptr_t instead and cast when you need to use the value or if that is not workable then both gcc and clang support a little documented work-around that should allow your particular use case.
Details
So clang is correct on this one if we go to the draft C++11 standard section 5.19 Constant expressions paragraph 2 says:
A conditional-expression is a core constant expression unless it
involves one of the following as a potentially evaluated subexpression
[...]
and includes the following bullet:
— a reinterpret_cast (5.2.10);
One simple solution would be to use intptr_t:
static constexpr intptr_t ptr = 0x1;
and then cast later on when you need to use it:
reinterpret_cast<void*>(foo::ptr) ;
It may be tempting to leave it at that but this story gets more interesting though. This is know and still open gcc bug see Bug 49171: [C++0x][constexpr] Constant expressions support reinterpret_cast. It is clear from the discussion that gcc devs have some clear use cases for this:
I believe I found a conforming usage of reinterpret_cast in constant
expressions useable in C++03:
//---------------- struct X { X* operator&(); };
X x[2];
const bool p = (reinterpret_cast<X*>(&reinterpret_cast<char&>(x[1]))
- reinterpret_cast<X*>(&reinterpret_cast<char&>(x[0]))) == sizeof(X);
enum E { e = p }; // e should have a value equal to 1
//----------------
Basically this program demonstrates the technique, the C++11 library
function addressof is based on and thus excluding reinterpret_cast
unconditionally from constant expressions in the core language would render this useful program invalid and would make it impossible to
declare addressof as a constexpr function.
but were not able to get an exception carved for these use cases, see closed issues 1384:
Although reinterpret_cast was permitted in address constant
expressions in C++03, this restriction has been implemented in some
compilers and has not proved to break significant amounts of code. CWG
deemed that the complications of dealing with pointers whose tpes
changed (pointer arithmetic and dereference could not be permitted on
such pointers) outweighed the possible utility of relaxing the current
restriction.
BUT apparently gcc and clang support a little documented extension that allows constant folding of non-constant expressions using __builtin_constant_p (exp) and so the following expressions is accepted by both gcc and clang:
static constexpr const void* ptr =
__builtin_constant_p( reinterpret_cast<const void*>(0x1) ) ?
reinterpret_cast<const void*>(0x1) : reinterpret_cast<const void*>(0x1) ;
Finding documentation for this is near impossible but this llvm commit is informative with the following snippets provide for some interesting reading:
support the gcc __builtin_constant_p() ? ... : ... folding hack in C++11
and:
// __builtin_constant_p ? : is magical, and is always a potential constant.
and:
// This macro forces its argument to be constant-folded, even if it's not
// otherwise a constant expression.
#define fold(x) (__builtin_constant_p(x) ? (x) : (x))
We can find a more formal explanation of this feature in the gcc-patches email: C constant expressions, VLAs etc. fixes which says:
Furthermore, the rules for __builtin_constant_p calls as conditional
expression condition in the implementation are more relaxed than those
in the formal model: the selected half of the conditional expression
is fully folded without regard to whether it is formally a constant
expression, since __builtin_constant_p tests a fully folded argument
itself.
Clang is right. The result of a reinterpret-cast is never a constant expression (cf. C++11 5.19/2).
The purpose of constant expressions is that they can be reasoned about as values, and values have to be valid. What you're writing is not provably a valid pointer (since it's not the address of an object, or related to the address of an object by pointer arithmetic), so you're not allowed to use it as a constant expression. If you just want to store the number 1, store it as a uintptr_t and do the reinterpret cast at the use site.
As an aside, to elaborate a bit on the notion of "valid pointers", consider the following constexpr pointers:
constexpr int const a[10] = { 1 };
constexpr int * p1 = a + 5;
constexpr int const b[10] = { 2 };
constexpr int const * p2 = b + 10;
// constexpr int const * p3 = b + 11; // Error, not a constant expression
static_assert(*p1 == 0, ""); // OK
// static_assert(p1[5] == 0, ""); // Error, not a constant expression
static_assert(p2[-2] == 0, ""); // OK
// static_assert(p2[1] == 0, ""); // Error, "p2[1]" would have UB
static_assert(p2 != nullptr, ""); // OK
// static_assert(p2 + 1 != nullptr, ""); // Error, "p2 + 1" would have UB
Both p1 and p2 are constant expressions. But whether the result of pointer arithmetic is a constant expression depends on whether it is not UB! This kind of reasoning would be essentially impossible if you allowed the values of reinterpret_casts to be constant expressions.
I have also been running into this problem when programming for AVR microcontrollers. Avr-libc has header files (included through <avr/io.h> that make available the register layout for each microcontroller by defining macros such as:
#define TCNT1 (*(volatile uint16_t *)(0x84))
This allows using TCNT1 as if it were a normal variable and any reads and writes are directed to memory address 0x84 automatically. However, it also includes an (implicit) reinterpret_cast, which prevents using the address of this "variable" in a constant expression. And since this macro is defined by avr-libc, changing it to remove the cast is not really an option (and redefining such macros yourself works, but then requires defining them for all the different AVR chips, duplicating the info from avr-libc).
Since the folding hack suggested by Shafik here seems to no longer work in gcc 7 and above, I have been looking for another solution.
Looking at the avr-libc header files more closely, it turns out they have two modes:
Normally, they define variable-like macros as shown above.
When used inside the assembler (or when included with _SFR_ASM_COMPAT defined), they define macros that just contain the address, e.g.:
#define TCNT1 (0x84)
At first glance the latter seems useful, since you could then set _SFR_ASM_COMPAT before include <avr/io.h> and simply use intptr_t constants and use the address directly, rather than through a pointer. However, since you can include the avr-libc header only once (iow, only have TCNT1 as either a variable-like-macro, or an address), this trick only works inside a source file that does not include any other files that would need the variable-like-macros. In practice, this seems unlikely (though maybe you could have constexpr (class?) variables that are declared in a .h file and assigned a value in a .cpp file that includes nothing else?).
In any case, I found another trick by Krister Walfridsson, that defines these registers as external variables in a C++ header file and then defines them and locates them at a fixed location by using an assembler .S file. Then you can simply take the address of these global symbols, which is valid in a constexpr expressions. To make this work, this global symbol must have a different name as the original register macro, to prevent a conflict between both.
E.g. in your C++ code, you would have:
extern volatile uint16_t TCNT1_SYMBOL;
struct foo {
static constexpr volatile uint16_t* ptr = &TCNT1_SYMBOL;
};
And then you include a .S file in your project that contains:
#include <avr/io.h>
.global TCNT1_SYMBOL
TCNT1_SYMBOL = TCNT1
While writing this, I realized the above is not limited to the AVR-libc case, but can also be applied to the more generic question asked here. In that case, you could get a C++ file that looks like:
extern char MY_PTR_SYMBOL;
struct foo {
static constexpr const void* ptr = &MY_PTR_SYMBOL;
};
auto main() -> int {
return 0;
}
And a .S file that looks like:
.global MY_PTR_SYMBOL
MY_PTR_SYMBOL = 0x1
Here's how this looks: https://godbolt.org/z/vAfaS6 (I could not figure out how to get the compiler explorer to link both the cpp and .S file together, though
This approach has quite a bit more boilerplate, but does seem to work reliably across gcc and clang versions. Note that this approach looks like a similar approach using linker commandline options or linker scripts to place symbols at a certain memory address, but that approach is highly non-portable and tricky to integrate in a build process, while the approach suggested above is more portable and just a matter of adding a .S file into the build.
As pointed out in the comments, there is a performance downside though: The address is no more known at compile time. This means the compiler can no more use IN, OUT, SBI, CBI, SBIC, SBIS instructions. This increases code size, makes code slower, increases register pressure and many sequences are no more atomic, hence will need extra code if atomic execution is needed (most of the cases).
This is not a universal answer, but it works with that special case of a struct with special function registers of an MCU peripheral at fixed address. A union could be used to convert integer to pointer. It is still undefined behavior, but this cast-by-union is widely used in an embedded area. And it works perfectly in GCC (tested up to 9.3.1).
struct PeripheralRegs
{
volatile uint32_t REG_A;
volatile uint32_t REG_B;
};
template<class Base, uintptr_t Addr>
struct SFR
{
union
{
uintptr_t addr;
Base* regs;
};
constexpr SFR() :
addr(Addr) {}
Base* operator->() const
{
return regs;
}
void wait_for_something() const
{
while (!regs->REG_B);
}
};
constexpr SFR<PeripheralRegs, 0x10000000> peripheral;
uint32_t fn()
{
peripheral.wait_for_something();
return peripheral->REG_A;
}
Consider the following piece of code:
struct foo {
static constexpr const void* ptr = reinterpret_cast<const void*>(0x1);
};
auto main() -> int {
return 0;
}
The above example compiles fine in g++ v4.9 (Live Demo), while it fails to compile in clang v3.4 (Live Demo) and generates the following error:
error: constexpr variable 'ptr' must be initialized by a constant expression
Questions:
Which of the two compilers is right according to the standard?
What's the proper way of declaring an expression of such kind?
TL;DR
clang is correct, this is known gcc bug. You can either use intptr_t instead and cast when you need to use the value or if that is not workable then both gcc and clang support a little documented work-around that should allow your particular use case.
Details
So clang is correct on this one if we go to the draft C++11 standard section 5.19 Constant expressions paragraph 2 says:
A conditional-expression is a core constant expression unless it
involves one of the following as a potentially evaluated subexpression
[...]
and includes the following bullet:
— a reinterpret_cast (5.2.10);
One simple solution would be to use intptr_t:
static constexpr intptr_t ptr = 0x1;
and then cast later on when you need to use it:
reinterpret_cast<void*>(foo::ptr) ;
It may be tempting to leave it at that but this story gets more interesting though. This is know and still open gcc bug see Bug 49171: [C++0x][constexpr] Constant expressions support reinterpret_cast. It is clear from the discussion that gcc devs have some clear use cases for this:
I believe I found a conforming usage of reinterpret_cast in constant
expressions useable in C++03:
//---------------- struct X { X* operator&(); };
X x[2];
const bool p = (reinterpret_cast<X*>(&reinterpret_cast<char&>(x[1]))
- reinterpret_cast<X*>(&reinterpret_cast<char&>(x[0]))) == sizeof(X);
enum E { e = p }; // e should have a value equal to 1
//----------------
Basically this program demonstrates the technique, the C++11 library
function addressof is based on and thus excluding reinterpret_cast
unconditionally from constant expressions in the core language would render this useful program invalid and would make it impossible to
declare addressof as a constexpr function.
but were not able to get an exception carved for these use cases, see closed issues 1384:
Although reinterpret_cast was permitted in address constant
expressions in C++03, this restriction has been implemented in some
compilers and has not proved to break significant amounts of code. CWG
deemed that the complications of dealing with pointers whose tpes
changed (pointer arithmetic and dereference could not be permitted on
such pointers) outweighed the possible utility of relaxing the current
restriction.
BUT apparently gcc and clang support a little documented extension that allows constant folding of non-constant expressions using __builtin_constant_p (exp) and so the following expressions is accepted by both gcc and clang:
static constexpr const void* ptr =
__builtin_constant_p( reinterpret_cast<const void*>(0x1) ) ?
reinterpret_cast<const void*>(0x1) : reinterpret_cast<const void*>(0x1) ;
Finding documentation for this is near impossible but this llvm commit is informative with the following snippets provide for some interesting reading:
support the gcc __builtin_constant_p() ? ... : ... folding hack in C++11
and:
// __builtin_constant_p ? : is magical, and is always a potential constant.
and:
// This macro forces its argument to be constant-folded, even if it's not
// otherwise a constant expression.
#define fold(x) (__builtin_constant_p(x) ? (x) : (x))
We can find a more formal explanation of this feature in the gcc-patches email: C constant expressions, VLAs etc. fixes which says:
Furthermore, the rules for __builtin_constant_p calls as conditional
expression condition in the implementation are more relaxed than those
in the formal model: the selected half of the conditional expression
is fully folded without regard to whether it is formally a constant
expression, since __builtin_constant_p tests a fully folded argument
itself.
Clang is right. The result of a reinterpret-cast is never a constant expression (cf. C++11 5.19/2).
The purpose of constant expressions is that they can be reasoned about as values, and values have to be valid. What you're writing is not provably a valid pointer (since it's not the address of an object, or related to the address of an object by pointer arithmetic), so you're not allowed to use it as a constant expression. If you just want to store the number 1, store it as a uintptr_t and do the reinterpret cast at the use site.
As an aside, to elaborate a bit on the notion of "valid pointers", consider the following constexpr pointers:
constexpr int const a[10] = { 1 };
constexpr int * p1 = a + 5;
constexpr int const b[10] = { 2 };
constexpr int const * p2 = b + 10;
// constexpr int const * p3 = b + 11; // Error, not a constant expression
static_assert(*p1 == 0, ""); // OK
// static_assert(p1[5] == 0, ""); // Error, not a constant expression
static_assert(p2[-2] == 0, ""); // OK
// static_assert(p2[1] == 0, ""); // Error, "p2[1]" would have UB
static_assert(p2 != nullptr, ""); // OK
// static_assert(p2 + 1 != nullptr, ""); // Error, "p2 + 1" would have UB
Both p1 and p2 are constant expressions. But whether the result of pointer arithmetic is a constant expression depends on whether it is not UB! This kind of reasoning would be essentially impossible if you allowed the values of reinterpret_casts to be constant expressions.
I have also been running into this problem when programming for AVR microcontrollers. Avr-libc has header files (included through <avr/io.h> that make available the register layout for each microcontroller by defining macros such as:
#define TCNT1 (*(volatile uint16_t *)(0x84))
This allows using TCNT1 as if it were a normal variable and any reads and writes are directed to memory address 0x84 automatically. However, it also includes an (implicit) reinterpret_cast, which prevents using the address of this "variable" in a constant expression. And since this macro is defined by avr-libc, changing it to remove the cast is not really an option (and redefining such macros yourself works, but then requires defining them for all the different AVR chips, duplicating the info from avr-libc).
Since the folding hack suggested by Shafik here seems to no longer work in gcc 7 and above, I have been looking for another solution.
Looking at the avr-libc header files more closely, it turns out they have two modes:
Normally, they define variable-like macros as shown above.
When used inside the assembler (or when included with _SFR_ASM_COMPAT defined), they define macros that just contain the address, e.g.:
#define TCNT1 (0x84)
At first glance the latter seems useful, since you could then set _SFR_ASM_COMPAT before include <avr/io.h> and simply use intptr_t constants and use the address directly, rather than through a pointer. However, since you can include the avr-libc header only once (iow, only have TCNT1 as either a variable-like-macro, or an address), this trick only works inside a source file that does not include any other files that would need the variable-like-macros. In practice, this seems unlikely (though maybe you could have constexpr (class?) variables that are declared in a .h file and assigned a value in a .cpp file that includes nothing else?).
In any case, I found another trick by Krister Walfridsson, that defines these registers as external variables in a C++ header file and then defines them and locates them at a fixed location by using an assembler .S file. Then you can simply take the address of these global symbols, which is valid in a constexpr expressions. To make this work, this global symbol must have a different name as the original register macro, to prevent a conflict between both.
E.g. in your C++ code, you would have:
extern volatile uint16_t TCNT1_SYMBOL;
struct foo {
static constexpr volatile uint16_t* ptr = &TCNT1_SYMBOL;
};
And then you include a .S file in your project that contains:
#include <avr/io.h>
.global TCNT1_SYMBOL
TCNT1_SYMBOL = TCNT1
While writing this, I realized the above is not limited to the AVR-libc case, but can also be applied to the more generic question asked here. In that case, you could get a C++ file that looks like:
extern char MY_PTR_SYMBOL;
struct foo {
static constexpr const void* ptr = &MY_PTR_SYMBOL;
};
auto main() -> int {
return 0;
}
And a .S file that looks like:
.global MY_PTR_SYMBOL
MY_PTR_SYMBOL = 0x1
Here's how this looks: https://godbolt.org/z/vAfaS6 (I could not figure out how to get the compiler explorer to link both the cpp and .S file together, though
This approach has quite a bit more boilerplate, but does seem to work reliably across gcc and clang versions. Note that this approach looks like a similar approach using linker commandline options or linker scripts to place symbols at a certain memory address, but that approach is highly non-portable and tricky to integrate in a build process, while the approach suggested above is more portable and just a matter of adding a .S file into the build.
As pointed out in the comments, there is a performance downside though: The address is no more known at compile time. This means the compiler can no more use IN, OUT, SBI, CBI, SBIC, SBIS instructions. This increases code size, makes code slower, increases register pressure and many sequences are no more atomic, hence will need extra code if atomic execution is needed (most of the cases).
This is not a universal answer, but it works with that special case of a struct with special function registers of an MCU peripheral at fixed address. A union could be used to convert integer to pointer. It is still undefined behavior, but this cast-by-union is widely used in an embedded area. And it works perfectly in GCC (tested up to 9.3.1).
struct PeripheralRegs
{
volatile uint32_t REG_A;
volatile uint32_t REG_B;
};
template<class Base, uintptr_t Addr>
struct SFR
{
union
{
uintptr_t addr;
Base* regs;
};
constexpr SFR() :
addr(Addr) {}
Base* operator->() const
{
return regs;
}
void wait_for_something() const
{
while (!regs->REG_B);
}
};
constexpr SFR<PeripheralRegs, 0x10000000> peripheral;
uint32_t fn()
{
peripheral.wait_for_something();
return peripheral->REG_A;
}
The code below performs a fast inverse square root operation by some bit hacks.
The algorithm was probably developed by Silicon Graphics in early 1990's and it's appeared in Quake 3 too.
more info
However I get the following warning from GCC C++ compiler: dereferencing type-punned pointer will break strict-aliasing rules
Should I use static_cast, reinterpret_cast or dynamic_cast instead in such situations?
float InverseSquareRoot(float x)
{
float xhalf = 0.5f*x;
int32_t i = *(int32_t*)&x;
i = 0x5f3759df - (i>>1);
x = *(float*)&i;
x = x*(1.5f - xhalf*x*x);
return x;
}
Forget casts. Use memcpy.
float xhalf = 0.5f*x;
uint32_t i;
assert(sizeof(x) == sizeof(i));
std::memcpy(&i, &x, sizeof(i));
i = 0x5f375a86 - (i>>1);
std::memcpy(&x, &i, sizeof(i));
x = x*(1.5f - xhalf*x*x);
return x;
The original code tries to initialize the int32_t by first accessing the float object through an int32_t pointer, which is where the rules are broken. The C-style cast is equivalent to a reinterpret_cast, so changing it to reinterpret_cast would not make much difference.
The important difference when using memcpy is that the bytes are copied from the float into the int32_t, but the float object is never accessed through an int32_t lvalue, because memcpy takes pointers to void and its insides are "magical" and don't break the aliasing rules.
There are a few good answers here that address the type-punning issue.
I want to address the "fast inverse square-root" part. Don't use this "trick" on modern processors. Every mainstream vector ISA has a dedicated hardware instruction to give you a fast inverse square-root. Every one of them is both faster and more accurate than this oft-copied little hack.
These instructions are all available via intrinsics, so they are relatively easy to use. In SSE, you want to use rsqrtss (intrinsic: _mm_rsqrt_ss( )); in NEON you want to use vrsqrte (intrinsic: vrsqrte_f32( )); and in AltiVec you want to use frsqrte. Most GPU ISAs have similar instructions. These estimates can be refined using the same Newton iteration, and NEON even has the vrsqrts instruction to do part of the refinement in a single instruction without needing to load constants.
Update
I no longer believe this answer is correct, due to feedback I've gotten from the committee. But I want to leave it up for informational purposes. And I am purposefully hopeful that this answer can be made correct by the committee (if it chooses to do so). I.e. there's nothing about the underlying hardware that makes this answer incorrect, it is just the judgement of a committee that makes it so, or not so.
I'm adding an answer not to refute the accepted answer, but to augment it. I believe the accepted answer is both correct and efficient (and I've just upvoted it). However I wanted to demonstrate another technique that is just as correct and efficient:
float InverseSquareRoot(float x)
{
union
{
float as_float;
int32_t as_int;
};
float xhalf = 0.5f*x;
as_float = x;
as_int = 0x5f3759df - (as_int>>1);
as_float = as_float*(1.5f - xhalf*as_float*as_float);
return as_float;
}
Using clang++ with optimization at -O3, I compiled plasmacel's code, R. Martinho Fernandes code, and this code, and compared the assembly line by line. All three were identical. This is due to the compiler's choice to compile it like this. It had been equally valid for the compiler to produce different, broken code.
If you have access to C++20 or later then you can use std::bit_cast
float InverseSquareRoot(float x)
{
float xhalf = 0.5f*x;
int32_t i = std::bit_cast<int32_t>(x);
i = 0x5f3759df - (i>>1);
x = std::bit_cast<float>(i);
x = x*(1.5f - xhalf*x*x);
return x;
}
At the moment std::bit_cast is only supported by MSVC. See demo on Godbolt
While waiting for the implementation, if you're using Clang you can try __builtin_bit_cast. Just change the casts like this
int32_t i = __builtin_bit_cast(std::int32_t, x);
x = __builtin_bit_cast(float, i);
Demo
Take a look at this for more information on type punning and strict aliasing.
The only safe cast of a type into an array is into a char array. If you want one data address to be switchable to different types you will need to use a union
The cast invokes undefined behaviour. No matter what form of cast you use, it will still be undefined behaviour. It is undefined no matter what type of cast you use.
Most compilers will do what you expect, but gcc likes being mean and is probably going to assume you didn't assign the pointers despite all indication you did and reorder the operation so they give some strange result.
Casting a pointer to incompatible type and dereferencing it is an undefined behaviour. The only exception is casting it to or from char, so the only workaround is using std::memcpy (as per R. Martinho Fernandes' answer). (I am not sure how much it is defined using unions; It does stand a better chance of working though).
That said, you should not use C-style cast in C++. In this case, static_cast would not compile, nor would dynamic_cast, forcing you to use reinterpret_cast and reinterpret_cast is a strong suggestion you might be violating strict aliasing rules.
Based on the answers here I made a modern "pseudo-cast" function for ease of application.
C99 version
(while most compilers support it, theoretically could be undefined behavior in some)
template <typename T, typename U>
inline T pseudo_cast(const U &x)
{
static_assert(std::is_trivially_copyable<T>::value && std::is_trivially_copyable<U>::value, "pseudo_cast can't handle types which are not trivially copyable");
union { U from; T to; } __x = {x};
return __x.to;
}
Universal versions
(based on the accepted answer)
Cast types with the same size:
#include <cstring>
template <typename T, typename U>
inline T pseudo_cast(const U &x)
{
static_assert(std::is_trivially_copyable<T>::value && std::is_trivially_copyable<U>::value, "pseudo_cast can't handle types which are not trivially copyable");
static_assert(sizeof(T) == sizeof(U), "pseudo_cast can't handle types with different size");
T to;
std::memcpy(&to, &x, sizeof(T));
return to;
}
Cast types with any sizes:
#include <cstring>
template <typename T, typename U>
inline T pseudo_cast(const U &x)
{
static_assert(std::is_trivially_copyable<T>::value && std::is_trivially_copyable<U>::value, "pseudo_cast can't handle types which are not trivially copyable");
T to = T(0);
std::memcpy(&to, &x, (sizeof(T) < sizeof(U)) ? sizeof(T) : sizeof(U));
return to;
}
Use it like:
float f = 3.14f;
uint32_t u = pseudo_cast<uint32_t>(f);
Update for C++20
C++20 introduces constexpr std::bit_cast in header <bit> which is functionally equivalent for types with the same size. Nevertheless, the above versions are still useful if you want to implement this functionality yourself (supposed that constexpr is not required), or if you want to support types with different sizes.
The only cast that will work here is reinterpret_cast. (And
even then, at least one compiler will go out of its way to
ensure that it won't work.)
But what are you actually trying to do? There's certainly
a better solution, that doesn't involve type punning. There are
very, very few cases where type punning is appropriate, and they
all are in very, very low level code, things like serialization,
or implementing the C standard library (e.g. functions like
modf). Otherwise (and maybe even in serialization), functions
like ldexp and modf will probably work better, and certainly
be more readable.
We just upgraded our compiler to gcc 4.6 and now we get some of these warnings. At the moment our codebase is not in a state to be compiled with c++0x and anyway, we don't want to run this in prod (at least not yet) - so I needed a fix to remove this warning.
The warnings occur typically because of something like this:
struct SomeDataPage
{
// members
char vData[SOME_SIZE];
};
later, this is used in the following way
SomeDataPage page;
new(page.vData) SomeType(); // non-trivial constructor
To read, update and return for example, the following cast used to happen
reinterpret_cast<SomeType*>(page.vData)->some_member();
This was okay with 4.4; in 4.6 the above generates:
warning: type punned pointer will break strict-aliasing rules
Now a clean way to remove this error is to use a union, however like I said, we can't use c++0x (and hence unrestricted unions), so I've employed the horrible hack below - now the warning has gone away, but am I likely to invoke nasal daemons?
static_cast<SomeType*>(reinterpret_cast<void*>(page.vData))->some_member();
This appears to work okay (see simple example here: http://www.ideone.com/9p3MS) and generates no warnings, is this okay(not in the stylistic sense) to use this till c++0x?
NOTE: I don't want to use -fno-strict-aliasing generally...
EDIT: It seems I was mistaken, the same warning is there on 4.4, I guess we only picked this up recently with the change (it was always unlikely to be a compiler issue), the question still stands though.
EDIT: further investigation yielded some interesting information, it seems that doing the cast and calling the member function in one line is what is causing the warning, if the code is split into two lines as follows
SomeType* ptr = reinterpret_cast<SomeType*>(page.vData);
ptr->some_method();
this actually does not generate a warning. As a result, my simple example on ideone is flawed and more importantly my hack above does not fix the warning, the only way to fix it is to split the function call from the cast - then the cast can be left as a reinterpret_cast.
SomeDataPage page;
new(page.vData) SomeType(); // non-trivial constructor
reinterpret_cast<SomeType*>(page.vData)->some_member();
This was okay with 4.4; in 4.6 the above generates:
warning: type punned pointer will break strict-aliasing rules
You can try:
SomeDataPage page;
SomeType *data = new(page.vData) SomeType(); // non-trivial constructor
data->some_member();
Why not use:
SomeType *item = new (page.vData) SomeType();
and then:
item->some_member ();
I don't think a union is the best way, it may also be problematic. From the gcc docs:
`-fstrict-aliasing'
Allows the compiler to assume the strictest aliasing rules
applicable to the language being compiled. For C (and C++), this
activates optimizations based on the type of expressions. In
particular, an object of one type is assumed never to reside at
the same address as an object of a different type, unless the
types are almost the same. For example, an `unsigned int' can
alias an `int', but not a `void*' or a `double'. A character type
may alias any other type.
Pay special attention to code like this:
union a_union {
int i;
double d;
};
int f() {
a_union t;
t.d = 3.0;
return t.i;
}
The practice of reading from a different union member than the one
most recently written to (called "type-punning") is common. Even
with `-fstrict-aliasing', type-punning is allowed, provided the
memory is accessed through the union type. So, the code above
will work as expected. However, this code might not:
int f() {
a_union t;
int* ip;
t.d = 3.0;
ip = &t.i;
return *ip;
}
How this relates to your problem is tricky to determine. I guess the compiler is not seeing the data in SomeType as the same as the data in vData.
I'd be more concerned about SOME_SIZE not being big enough, frankly. However, it is legal to alias any type with a char*. So simply doing reinterpret_cast<T*>(&page.vData[0]) should be just fine.
Also, I'd question this kind of design. Unless you're implementing boost::variant or something similar, there's not much reason to use it.
struct SomeDataPage
{
// members
char vData[SOME_SIZE];
};
This is problematic for aliasing/alignment reasons. For one, the alignment of this struct isn't necessarily the same as the type you're trying to pun inside it. You could try using GCC attributes to enforce a certain alignment:
struct SomeDataPage { char vData[SOME_SIZE] __attribute__((aligned(16))); };
Where alignment of 16 should be adequate for anything I've come across. Then again, the compiler still won't like your code, but it won't break if the alignment is good. Alternatively, you could use the new C++0x alignof/alignas.
template <class T>
struct DataPage {
alignof(T) char vData[sizeof(T)];
};