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.
>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