← Back to C++ Course | Chapter 17: Advanced C++ | Lesson 11 of 17

C++ reinterpret_cast

What is reinterpret_cast?

The reinterpret_cast operator performs low-level, binary-level type conversions. It treats the raw bit pattern of an object as if it were a completely different type, without converting the data.

Example: What is reinterpret_cast?

cpp
#include <iostream>

int main() {
	int x = 65;
	char *p = reinterpret_cast<char *>(&x); // treats raw bits as a different type
	std::cout << *p << std::endl;
	return 0;
}

Pointer to Integer Conversions

You can use reinterpret_cast to convert a memory address (a pointer) to an integer value. This is useful for low-level logging or system-level debugging. Unlike static_cast, reinterpret_cast performs no safety checks or value conversion, it just reinterprets the same bits differently.

Example: Pointer to Integer Conversions

cpp
#include <iostream>

int main() {
	int x = 5;
	int *ptr = &x;
	long address = reinterpret_cast<long>(ptr); // pointer to integer
	std::cout << "Address as number: " << address << std::endl;
	return 0;
}

Working with Byte Streams

Reinterpret_cast is often used to convert structured data (such as a struct) into a raw byte stream (char). This is necessary for serializing and sending data over networks. Because it bypasses type safety entirely, the resulting byte layout is platform-dependent and should be used with real caution.

Example: Working with Byte Streams

cpp
#include <iostream>

struct Point { int x; int y; };

int main() {
	Point p = {1, 2};
	char *bytes = reinterpret_cast<char *>(&p); // struct viewed as raw bytes
	std::cout << (int)bytes[0] << std::endl;
	return 0;
}

Casting Function Pointers

You can use reinterpret_cast to convert one function pointer type to another. This is occasionally used in system programming to store diverse function pointers inside a single array.

Example: Casting Function Pointers

cpp
#include <iostream>

void hello() { std::cout << "Hello" << std::endl; }

int main() {
	void *generic = reinterpret_cast<void *>(hello);
	void (*fn)() = reinterpret_cast<void (*)()>(generic); // back to a function pointer
	fn();
	return 0;
}

Security and Portability Risks

Because reinterpret_cast bypasses C++ type safety entirely, it is highly non-portable and risky. It can easily lead to undefined behavior or memory access errors if used incorrectly.

Example: Security and Portability Risks

cpp
#include <iostream>

int main() {
	float f = 3.14f;
	int *misread = reinterpret_cast<int *>(&f); // bypasses type safety entirely
	std::cout << "Bit pattern misread as int: " << *misread << std::endl;
	return 0;
}

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.