What happens when we cross the range of int variable in c++??
Namaste,
So, basically, some points to note I am not sure that what I am going to tell is valid or not …..or maybe I do not use the correct words for that ….so please cut me some slack.
Now, when I started learning the topic “ DIFFERENT DATA TYPES “ I encountered this …really weird thing going on …c++…
so when I write this code … I am assuming that I am going to get an error because I cross the range of int but naaaa!!! WTF!! I see that I get -1 as output and then I increase the value of variable “b” by +2
then I again compile and get the output as 1
and then damn… I was like…what is this shit !!!!
but after some time … I notice a pattern that …after increasing the value of variable “b” by +1 the value of output also increases by 1 …
so what actually the compiler did is that …instead of showing error when you cross the range of int ….it started storing a negative value in variable “b”…
Let me explain …which neg value and how it is going to store
just assume you make a variable and store a value that crosses the range
int b = 2147483648;
so instead of storing 2147483648 in variable “b”, it stores the value -2147483648
now let's take another example ….
int b = 2147483649;
now this time in variable “b” stores the value -2147483647
Now let's start playing with this cool thing.
Increase the value of b by +1
int b = 2147483650;
this time b stores the value -2147483646
int b = 2147483651;
this time b stores the value -2147483645
int b = 2147483652;
this time b stores the value -2147483644
“ I hope you get the pattern …..”
BUT THERE IS ALSO ONE THING TO NOTE …..that the range of int is from -2147483648 to 2147483647
that’s why when we assign value 2147483648 to “b” it stores the value -2147483648 and after that, it starts …back counting in the negative sense …..
ATLAST, I WANT TO TAKE A DEEP BREATH AND PRAYING TO THE BHAGWAN THAT YOU GET WHAT I WANTED TO TELL YOU 😂😂😂
BUT THAT FUN FACT IS THIS …I JUST ENCOUNTERED THIS PATTERN BUT STILL, I AM NOT ABLE TO FIGURE OUT …WHY THIS THING WAS HAPPENING …WHY INSTEAD OF SHOWING ERROR IT STARTED ASSIGNING NEGATIVE VALUE IN THIS PATTERN …..
“ IF ANY ONE GETS THE ANSWER OF THIS WHY, PLEASE TELL ME”
DHANYWAAD..!!!!!