Data types
and their
coding methods
-
Review:
the primitive
data types and
their
coding methods
-
Programming rule:
-
Values of a
data type
must
be
stored using its
encoding method
|
I.e.:
- int
typed variables
must
store their
value in
2s complement code
- float
typed variable will
must
store their
value in
IEEE 754 code
- And so on...
|
|
Assigning
values to a variable
-
Programming rule:
-
Values of a
data type
must
be
stored using its
encoding method
|
- Consequence
of the
programming rule:
- If you store
a value of
different
a
data type into
a variable:
- The compiler will
convert the
value into
data type of the
target variable
before storing it in
the variable
|
|
Example:
float x;
x = 3; // 3 (2s compl code) will first be converted to 3.0 (IEE 754)
// Then 3.0 (IEEE 754) is assigned to x
|
|
Different behavior
in the assignment operation in
C
-
Java does
not allow
assignment of a
wider
typed value to a
narrower
typed variable
(due to lost of
data)
Example:
short x;
int y;
x = y ; // Java disallow assignment of
// a double value to an int variable
// without casting
|
- Java
requires
a
casting (conversion) operation:
|
DEMO:
demo/C/set1/javaCasting.java
(seen it before)
Different behavior
in the assignment operation in
C
-
C
in contrast does
allow
assignment of a
wider typed value to a
narrower typed variable
Example:
int main(int argc, char* argv[] )
{
short x;
int y;
x = 99; y = 65536 + 4; // Initialize
y = x; // short --> int is safe
printf("short x = %d, int y = %d\n", x, y);
x = 99; y = 65536 + 4; // Initialize
x = y; // int --> short is UNSAFE --- C permits it !!!
printf("short x = %d, int y = %d\n", x, y);
}
|
|
DEMO:
demo/C/set1/c-casting.c
(seen it before)
Make the
C compiler print out
warning messages
on dangerous casting operations
- The C compiler
option
-Wconversion will
print out
warning messages
when an assignment uses
a wider data tye:
gcc -Wconversion casting01a.c
|
(-W stands for
warning)
|
(Seen it before)
❮
❯