Datatypes
Datatypes
Datatypes
T.JEYA.,ASSISTANT PROFESSOR.,
DEPARTMENT OF COMPUTER SCIENCE,
SAC WOMEN’S COLLEGE,CUMBUM.
Data types in C
Only really four basic types:
char
int (short, long, long long, unsigned)
float
double
In C:
return (new_c);
}
Integers
Fundamental problem:
Fixed-size representation can’t encode all numbers
2’s Complement
TMinn … TMaxn = -2n-1 … 2n-1-1:
32 bits: -2,147,483,648 ... 2,147,483,647 int
64 bits: -9,223,372,036,854,775,808 … 9,223,372,036,854,775,807 long int
0 0 1 1 =3 1 1 0 1 = -3
0 1 1 0 =6 1 0 1 0 = -6
0 1 1 1 =7 1 0 0 1 =9
0 0 1 1 =3 0 1 0 0 =4
Always rounds down!
0 1 1 1 =7 1 0 0 1 = -7
0 0 1 1 =3 1 1 0 0 = -4
Always rounds down!
Bit Shifting for Multiplication/Division
Why useful?
Simpler, thus faster, than general multiplication &
division
Standard compiler optimization
?
unsigned int u;
… ? What’s wrong?
if (u > -1) …
Fixed-size representations
Rational numbers (i.e., pairs of integers)
Fixed-point (use integer, remember where point is)
Floating-point (scientific notation)
Variable-size representations
Sums of fractions (e.g., Taylor-series)
Unbounded-length series of digits/bits
Floating-point
1.001101110 × 25 = 100110.1110
= 32 + 4 + 2 + 1/2 + 1/4 +
1
/8
= 38.875
binary point
FP Overflow & Underflow
Fixed-sized representation leads to limitations
Round Round
to - Zero to +
1.001101110 × 25
significand exponent
Fixed-size representation
Using more significand bits increased precision
Using more exponent bits increased range
Single-precision (float)
One word: 1 sign bit, 23 bit fraction, 8 bit exponent
Positive range: 1.17549435 × 10-38 … 3.40282347 × 10+38
Double-precision (double)
Two words: 1 sign bit, 52 bit fraction, 11 bit exponent
Positive range: 2.2250738585072014 × 10-308 … 1.7976931348623157
× 10+308
+0.0, -0.0
+, -
NaN: “Not a number”
int i = 20 / 3;
float f = 20.0 / 3.0;
int i = 1000 / 6;
float f = 1000.0 / 6.0;
Surprise!
Arithmetic in binary, printing in decimal –
doesn’t always give expected result
FP Integer Conversions in C
#include <limits.h>
#include <stdio.h>
int
main(void)
{
unsigned int ui = UINT_MAX;
float f = ui;
printf(“ui: %u\nf: %f\n”, ui, (double)f);
}
ui: 4294967295
f: 4294967296.000000
FP Integer Conversions in C
int i = 3.3 * 5;
float f = i;
f= ? 16.0
integer FP: FP integer:
Can lose precision Truncate fraction
If out of range,
Rounds, if necessary
undefined – not error
32-bit int fits in
double-precision FP
FP Behavior
Programmer must be aware of accuracy limitations!
Dealing with this is a subject of classes like CAAM 453
#include <stdbool.h>
Important!
bool bool1 = true; Compiler needs this or it
won't know about "bool"!
bool bool2 = false;
Not enforced in C
Actually just integers
Can assign values outside of the enumeration
Could cause bugs
Enumerated Types in C
enum Color { RED, WHITE, BLACK, YELLOW };
enum Color my_color = RED;