← Previous | 🏠 Homepage | Next Chapter → |
int
be?16-bit system (Turbo C):
int
= -32,768 to +32,76732-bit system (VC++):
int
= -2,147,483,648 to +2,147,483,647
Top bit = sign
1
= Negative0 = Positive
Old 16-bit code may not work on new systems (like Itanium ).
Long and Short
-
Want more space? Use
long
. Want to save space? Useshort
. -
Usual sizes:
-
short
→ 2 bytes -
long
→ 4 bytes
-
-
Syntax:
short int a;
or justshort a;
long int b;
or justlong b;
-
Want to force a constant to be long? Use
L
like a boss:
23L
(Not to be confused with 23 liters of Coke)
Signed & Unsigned – Mood Settings for Variables
Only Positive Vibes? Use unsigned
!
By default, int
can be positive or negative.
But if you only want positives (like for counting people):
unsigned int num;
Doubles the positive range
No minus signs = no wasted space!
Also works with:
-
unsigned short
-
unsigned long
Chars – Small but Tricky
- Normally,
char
stores ASCII values (like'A' = 65
) -
But
char
can also be signed or unsigned:-
signed char
= -128 to +127 -
unsigned char
= 0 to 255
-
-
Beware: Storing big numbers like
char ch = 291;
causes weird behavior.
Why? Becausechar
overflows and wraps around. So 291 turns into 35 – like magic, but evil.
Infinite Loop Example:
printf("%d %c", ch, ch);
Looks fine? But surprise! It's an infinite loop. Why?
Because char
can't go beyond 127. After that, it jumps to -128. Round and round it goes like a washing machine.
Fix it: Use int ch;
or do this trick:
unsigned char ch;
for (ch = 0; ch <= 254; ch++)
printf("%d %c", ch, ch);
printf("%d %c", ch, ch);
Floats, Doubles & Long Doubles – Surfing Real Numbers
float
– 4 bytes, good enough for daily math-
double
– 8 bytes, more accurate -
long double
– 10 bytes, for super nerdy numbers like black hole physics
Declaration:
float x;
double y;
long double z;
Format Specifiers (very important!):
-
%f
– float -
%lf
– double -
%Lf
– long double
Data Type Cheatsheet:
Type |
Range | Bytes | Format |
---|---|---|---|
signed char |
-128 to +127 |
1 |
|
unsigned char | 0 to 255 | 1 | %c |
short signed int | -32768 to +32767 | 2 | %d |
short unsigned int | 0 to 65535 | 2 | %u |
signed int | -32768 to +32767 | 2 | %d |
unsigned int | 0 to 65535 | 2 | %u |
long signed int | -2147483648 to +2147483647 | 4 | %ld |
long unsigned int | 0 to 4294967295 | 4 | %lu |
float | -3.4e38 to +3.4e38 | 4 | %f |
double | -1.7e308 to +1.7e308 | 8 | %lf |
long double | -1.7e4932 to +1.7e4932 | 10 | %Lf |
No comments:
Post a Comment