I have the following function:
size_t calc_allign(size_t num) {
return ((num + 7) & (-8)) - num;
}
And want to use it like this:
int start_allign = calc_align (sbrk(0));
But I am getting error:
error: no matching function for call to 'calc_align'
candidate function not viable: cannot convert argument of incomplete type 'void *' to 'size_t' (aka 'unsigned long') for 1st argument
size_t calc_align(size_t num) {
How may I convert void* ie a pointer to number? is that even something legal?
You can
reinterpret_casta pointer type tostd::uintptr_t(or the signed equivalent). You can then further convert to another integer type such asstd::size_tand that conversion can be implicit. In theory, the latter conversion may be lossy on systems wherestd::size_tis a smaller type.However, as far as the C++ language is concerned, there are no guarantees about the resulting number other than converting it back from
std::uintptr_tto the same pointer type will result in the same pointer value.Example:
The behaviour of explicit conversion aka C-style cast depend on the type of the operand. Some casts are unsafe while others are benign. Often simple mistakes cause intended safe cast to be unintendedly unsafe, leading to undefined behaviour (which is very bad) - while the proper C++ style cast would result in compilation error, leading to detection of the mistake (which is very good).
In case of reinterpret_cast, we are doing such unsafe cast so there is no safety aspect, but instead the importance of C++ style cast is to communicate that lack of safety to the reader of the program.
Don't use the C-style casts in C++. You don't need them for anything.