This article discusses typecasting of variables.
Type means various C type such as int
, char
, float
etc and casting it to different type.
We will discuss how is done, where is data lost; where casting is not necessary. Lets take small example first
#include <stdio.h> int main() { int i = 6000; char c; c = i; printf("i is %d, c is %d\n", i, c); }
Lets compile it as follow
$ gcc a.c -Wconversion
-Wconversion
tells to compiler to print a warning if assignment is loosing precision of data.
Here we are assigning a integer into a character type (which can hold value from 0 - 255).
We get compiler warning
$ gcc a.c -Wconversion
a.c: In function ‘main’:
a.c:7:8: warning: conversion to ‘char’ from ‘int’ may alter its value [-Wconversion]
c = i;
When i
is assigned to c
only 8 bits out of 6000
is stored.
The hex representation of 6000
is 0x1770
lower 8 bits is 0x70
which is 112 which is assigned to c.
We of course know that value of variable is lost if you still want to go ahead with the assigned, typecasting could be used.
#include <stdio.h> int main() { int i = 6000; char c; c = (char)i; printf("i is %d, c is %d\n", i, c); }
With above typecasting, warning is gone. Typecasting is telling compiler that there is change in type i know it, don't complain. Since programmer is taking some responsibility here, typecasting should be used with care.
Now lets assign a double variable to char
#include <stdio.h> int main() { double d = 400.1; char c; c = (char)d; printf("d is %lf, c is %d\n", d, c); }
d is 400.100000, c is -112
Now double is stored internally in 8 bytes using IEEE notation which we wont go in details. It would store 400 and 0.1 separately in it. When such assigned to character only 400 is assigned to it. Hex of 400 is 0x190. Hence only 0x90 (8 bit is assigned). Which is 144 (unsigned) or -112 (signed) char value.
Links
- Next Article - C Programming #71: Typecasting pointer
- Previous Article - C Programming #69: Volatile pointers
- All Article - C Programming
No comments :
Post a Comment