View previous topic :: View next topic |
Author |
Message |
s_mack
Joined: 04 Jun 2009 Posts: 107
|
Real simple Q about data type conversion |
Posted: Thu Aug 27, 2009 10:32 am |
|
|
Normally I'd just run this test myself but how the setup is here I can't actually see the results of our code on a console.
Real simple...
Code: |
float test;
float bar = 123.456;
int8 foo;
foo = (int8)bar;
test = bar;
|
Would test now be 123.456 or 123.0? In other words, did the (int8)bar covert bar to an int8 or did it just assign foo a value of an int8 converted bar but left bar alone as a float?
Thanks.
This is with a PIC18F4480. |
|
|
Ttelmah Guest
|
|
Posted: Thu Aug 27, 2009 10:40 am |
|
|
A cast (the name for the 'type' in brackets, used to convert a value type), does nothing to the original value. All it does is change the type for the operation involved.
So 'bar' is still 123.456.
In fact the cast is unecessary as shown, since C implicitly performs a hidden ast if values ar moved into other types.
Where it'd give a different result, is if arithmetic is involved.
For instance:
Code: |
float bar=123.567;
int8 foo;
foo = bar; //foo is now 123, and bar 123.567
foo = (int8)bar; //same result
foo = bar*2; //foo is now 247. Becasue bar is a float, fp arithmetic is
//used, 123.567*2 = 247.134, so foo becomes 247
foo = (int8)bar*2; //foo is now 246. Becasue bar is converted to int
//for the operation, 123*2 = 246
|
Best Wishes |
|
|
s_mack
Joined: 04 Jun 2009 Posts: 107
|
|
Posted: Thu Aug 27, 2009 10:42 am |
|
|
perfect, thank you. Exactly the kind of response I was looking for. |
|
|
mkuang
Joined: 14 Dec 2007 Posts: 257
|
Re: Real simple Q about data type conversion |
Posted: Thu Aug 27, 2009 11:04 am |
|
|
s_mack wrote: | Normally I'd just run this test myself but how the setup Code: |
float test;
float bar = 123.456;
int8 foo;
foo = (int8)bar;
test = bar;
|
|
You didn't overwrite bar at any point. So test = 123.456. Simple. The statement:
foo = (int8)bar takes bar, converts to integer, and assign that value to foo. The value of bar is left unchanged. |
|
|
|