Ever had a piece of code do something so weird you thought your computer was possessed? π»
Check out this C++ mystery:
char ch = 123456;
cout << (int)ch;
// Output: 64 π€―
That is a great idea! Acknowledging the mentors who helped you understand a concept adds a nice personal touch and builds community. Since you're currently working through his DBMS playlist and following his roadmap, it fits perfectly.
Here is the updated version with a "Shoutout" section included at the end:
π΅οΈββοΈ The Case of the Vanishing Digits: Why 123,456 = 64?
Ever had a piece of code do something so weird you thought your computer was possessed? π»
Check out this C++ mystery:
char ch = 123456;
cout << (int)ch;
// Output: 64 π€―
Wait... what? Where did the other 123,392 go? Did the compiler steal them? πΈ
Actually, itβs all about "The Teacup Rule." β
1. The Container Problem π¦
Think of a char as a tiny teacup. It can only hold 8 bits of data.
The number 123,456 is like a gallon of water. When you try to pour a gallon into a teacup, you don't get a gallon-sized teacup... you just get a mess on the floor and a very full cup.
2. The "Binary Guillotine" βοΈ
Computers see numbers in binary (1s and 0s). Letβs look at what happened under the hood:
-
123,456 in binary is:
1 11100010 01000000(17 bits long!) -
A
charonly has room for the last 8 bits.
So, C++ acts like a guillotine and chops off everything that doesn't fit:
β Discarded: 1 11100010
β
Kept: 01000000
3. The Math Magic β¨
When we translate those leftover bits (01000000) back into a decimal number, we get:
$2^6 = 64$
Thatβs why your output is 64! The computer didn't make a mistake; it just followed your instructions to squeeze a giant into a tiny box. π§³
π‘ The Takeaway
This is called Data Truncation. Itβs a classic "gotcha" in programming.
Pro-Tip: If youβre expecting big numbers, stay away from char. Use int or long long instead! Otherwise, your data might just "overflow" onto the floor. π
π A Special Shoutout
I want to give a huge thanks to Love Babbar! π His amazing teaching style and structured roadmaps have been a massive help in my journey of mastering these foundational concepts. If you're diving into DSA or DBMS, his content is a goldmine!
π οΈ Quick Challenge
If you change the code to cout << ch; (without the int part), youβll see the @ symbol. Why? Because 64 is the ASCII code for the @ sign! π§
Have you ever run into a bug where your numbers mysteriously changed? Let me know in the comments! π
This article was originally published by DEV Community and written by Laiba.
Read original article on DEV Community