Convert int to a char in C++
This post will discuss how to convert an int to a char in C++.
One way to convert an int to a char in C++ is to use type casting. Type casting is a way of explicitly changing the data type of a value or an expression. There are different types of type casting in C++, such as static_cast
, dynamic_cast
, reinterpret_cast
, or const_cast
.
1. Using C-style Cast
C-style cast is the simplest and most common type of type casting for converting an int to a char. To use the C-style cast to convert an int to a char, we need to enclose the int value or expression in parentheses and precede it with the char data type. For example, if we want to convert the int value 97
to the char value ‘a’, we can do something like this:
1 2 3 4 5 6 7 8 9 10 11 |
#include <iostream> int main() { int i = 97; char ch = i; std::cout << ch << std::endl; // a return 0; } |
2. Using Static Cast
A better, safer option to cast an integer to a char is using static_cast
. Static cast performs compile-time checks and conversions between compatible data types. It is safer and more reliable than the C-style cast, as it can detect and prevent invalid conversions or errors. To use static cast to convert an int to a char, we need to enclose the int value or expression in angle brackets and precede it with the static_cast
keyword and the char data type. For example:
1 2 3 4 5 6 7 8 9 10 11 12 |
#include <iostream> int main() { int i = 97; char ch = static_cast<char>(i); std::cout << ch << std::endl; // a return 0; } |
That’s all about converting an int to a char in C++.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)