Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

c++ how a char variable more than 128 output

Here is my code:

#include <bits/stdc++.h>
using namespace std;
int main(){
    char a = 129;
    printf("%d", a);
}

OUTPUT:-127
I want to konw how 129 changes to -127.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

It is a little bit of code you have, but you can learn a lot from it already.
One is to never ignore compiler warnings 🙂

Here is some modified code to help you explain things :

// #include <bits/stdc++.h> // NO never use this it is NOT a standard header file 
// using namespace std; // NO never use using namespace std; (using namespace is not recommended at all in big projects).

#include <iostream> // for console output
#include <format>   // C++20 replacement for printf
#include <limits>   // get information on maximum and minimum values

int main() 
{
    // NEVER ignore your compiler warnings. The compiler already warns value will not fit!!!
    // \temp\main.cpp(11,14): warning C4309: 'initializing': truncation of constant value
    char a = 129; // a signed char will not hold this.
    // printf("%d", a); // printf can be used, but is considered "unsafe" (can lead to buffer overflows)

    std::cout << std::format("the value of your number {}\n", a); // C++20

    // in the following code the casts are necessary to convert from char to a size value (otherwise output will show control characters)
    std::cout << "the minimum value in a char = " << static_cast<std::size_t>(std::numeric_limits<char>::min()) << "\n"; 
    std::cout << "the maximum value in a char = " << static_cast<std::size_t>(std::numeric_limits<char>::max()) << "\n";

    std::cout << "the minimum value in an unsigned char = " << static_cast<std::size_t>(std::numeric_limits<unsigned char>::min()) << "\n";
    std::cout << "the maximum value in an unsigned char = " << static_cast<std::size_t>(std::numeric_limits<unsigned char>::max()) << "\n";

    return 0;
}

So you have a choice to make, use numbers <129 or change to unsigned char.
or std::uint8_t

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading