473,804 Members | 3,123 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

two meanings of a cast

I haven't been thinking about it for years but recently I've stumbled on
the fact that 'casting' is actually doing (at least) two different
things:

On the one hand 'casting' means: 'Change something into somthing
else'. Example: double d=9.99; long l=(double)d;

On the other hand 'casting' means: 'Treating something as something
else without change'. For instance when casting function pointers.

Would You agree?

IMO this difference between 'conversion' and 'treatment' isn't probably
pointed out enough to C newcomers and may be one reason for the danger
of casts.

Felix
Apr 27 '07 #1
18 2217
Felix Kater wrote:
I haven't been thinking about it for years but recently I've stumbled on
the fact that 'casting' is actually doing (at least) two different
things:

On the one hand 'casting' means: 'Change something into somthing
else'. Example: double d=9.99; long l=(double)d;

On the other hand 'casting' means: 'Treating something as something
else without change'. For instance when casting function pointers.

Would You agree?
No.

In a cast expression `(T) E`, we're requiring the value of the expression
`E` to be converted to type `T` using the appropriate conversion machinery.

That's true everywhere.

Sometimes, the "appropriat e conversion machinery" leaves the underlying
bit-pattern unchanged, leading to the illusion that the cast means "Treat
something as something else without change". But this is an accident of
implementation.

[We have seen in the past that conversion from say `char*` to `int*` and
back requires bit-fiddling code in some implementations .]
IMO this difference between 'conversion' and 'treatment' isn't probably
pointed out enough to C newcomers and may be one reason for the danger
of casts.
I don't think it's as simple as that. I suspect the danger comes from
casts of pointers and a belief that if `p` points somewhere sane then
the pointer `(T*) p` points somewhere equally sane and is dereferencable
to get values of type `T`.

--
Nit-picking is best done among friends.

Hewlett-Packard Limited Cain Road, Bracknell, registered no:
registered office: Berks RG12 1HN 690597 England

Apr 27 '07 #2
>>>>"FK" == Felix Kater <fk****@googlem ail.comwrites:

FKOn the one hand 'casting' means: 'Change something into
FKsomthing else'. Example: double d=9.99; long l=(double)d;

FKOn the other hand 'casting' means: 'Treating something as
FKsomething else without change'. For instance when casting
FKfunction pointers.

FKWould You agree?

No; in your first case, you're also "treating something as something
else without change." The value of d does not change when you cast it
to a double (completely unnecessary, since that's what it is) and
assign it to l.

Charlton

--
Charlton Wilbur
cw*****@chromat ico.net
Apr 27 '07 #3
On Apr 27, 1:23 pm, Chris Dollin <chris.dol...@h p.comwrote:

<snip>
Sometimes, the "appropriat e conversion machinery" leaves the underlying
bit-pattern unchanged, leading to the illusion that the cast means "Treat
something as something else without change". But this is an accident of
implementation.
<snip>

Are you saying here that there exists an implementation that would
alter the bit pattern of an object as it is cast [keeping the
original's size constant] - or that the change in bits would likely be
the result of changing the size of the original?

Apr 27 '07 #4
Felix Kater wrote:
I haven't been thinking about it for years but recently I've stumbled on
the fact that 'casting' is actually doing (at least) two different
things:

On the one hand 'casting' means: 'Change something into somthing
else'. Example: double d=9.99; long l=(double)d;
That's fine, although it's a silly cast. `d' is already
a `double', so "converting " it to a `double' is unnecessary.
(The `double' result, whether "converted" or not, will then
be converted to `long' for initializing `l'.)
On the other hand 'casting' means: 'Treating something as something
else without change'. For instance when casting function pointers.

Would You agree?
No. A cast is an operator that performs a conversion (even
if the conversion is vacuous, as above). There is no such thing
as a "let's pretend" cast.

However, casts can convert a pointer of one type into a pointer
to another type, and there is something like a "let's pretend"
effect if the converted result is then used to access a pointed-
to object or function:

int i = 42;
unsigned char *p = (unsigned char*) &i;
printf ("The individual bytes of %d are:", i);
while (p < (unsigned char*)(&i + 1))
printf (" %d", *p++);
printf ("\n");

Line two takes the pointer-to-int value `&i' and converts
it to a pointer-to-unsigned-char, which it then stores in `p'.
There is no "let's pretend" at all: A value is converted from one
type to another, and that's that.

There's another such conversion on line four, where another
pointer-to-int is converted to pointer-to-unsigned-char for
purposes of comparison. Again, there's no "let's pretend:" the
cast converts the value `(&i + 1)' to a different type.

The "let's pretend" occurs on line five, where a pointer
to one type (unsigned char) is used to manipulate an object of
a different type (int). Observe that there is no cast in line
five: We are "treating something as something else without
change" by accessing it with different kinds of pointers, not
by applying a cast to it. (No cast is ever applied to `i'.)
IMO this difference between 'conversion' and 'treatment' isn't probably
pointed out enough to C newcomers and may be one reason for the danger
of casts.
It would be a disservice to newcomers to point out a difference
that doesn't exist. For the same reason, most introductory texts
omit mentioning the temperatures of C's data types.

--
Eric Sosman
es*****@acm-dot-org.invalid
Apr 27 '07 #5
On Fri, 27 Apr 2007 13:23:31 +0100
Chris Dollin <ch**********@h p.comwrote:
Sometimes, the "appropriat e conversion machinery" leaves the
underlying bit-pattern unchanged, leading to the illusion that the
cast means "Treat something as something else without change". But
this is an accident of implementation.
Some notes:

'sometimes': This is exactly what I mean--from a students view. Talking
about casts does not give you the clue if data is converted or not.

'illusion': In practice it *is* a big difference if you can or cannot
cast something into somthing else and back again without having changed
a single byte. So calling it an illusion wouldn't help.

'accident of implementation' : I wonder if there aren't cases in which
legal casts could simply never be 'conversions' nor make sense
as such in any implementation. So, this was reason why casts are ment
not to be conversions sometimes.

Felix
Apr 27 '07 #6
On Fri, 27 Apr 2007 08:58:24 -0400
Eric Sosman <es*****@acm-dot-org.invalidwrot e:
Example: double d=9.99; long l=(double)d;

'd' is already a `double', so "converting " it to a `double' is
unnecessary.
True, that was a silly mistake: I meant:
Example: double d=9.99; long l=(long)d;

Felix
Apr 27 '07 #7
"pemo" <pe*********@gm ail.comha scritto nel messaggio
news:11******** **************@ c18g2000prb.goo glegroups.com.. .
Are you saying here that there exists an implementation that would
alter the bit pattern of an object as it is cast [keeping the
original's size constant] - or that the change in bits would likely be
the result of changing the size of the original?
If sizeof(int) equals sizeof(float), do you expect

int i = SOME_INTEGER_CO NSTANT;
float f = (float)i;

!memcmp(&i, &f, sizeof i)

to always be true, on *any* implementation?
Apr 27 '07 #8
pemo wrote:
On Apr 27, 1:23 pm, Chris Dollin <chris.dol...@h p.comwrote:
>Sometimes, the "appropriat e conversion machinery" leaves the underlying
bit-pattern unchanged, leading to the illusion that the cast means "Treat
something as something else without change". But this is an accident of
implementation .

Are you saying here that there exists an implementation that would
alter the bit pattern of an object as it is cast [keeping the
original's size constant] - or that the change in bits would likely be
the result of changing the size of the original?
No, I'm saying that sometimes the conversion doesn't alter the bitpattern,
so looking at the bitpattern gives the illusion that the cast doesn't
really do anything.

(EG one could play with `unsigned char *` to discover the values of the
bytes and that the bytes of the converted value were equal to the bytes
of the original value; or one could read the assembler output of a
I-can-do-assembler-output compiler.)

This will happen with eg casting ints to longs and vice-versa on machines
where they're the same size, and often happens with casting between
object pointer values.

--
"Who do you serve, and who do you trust?" /Crusade/

Hewlett-Packard Limited registered no:
registered office: Cain Road, Bracknell, Berks RG12 1HN 690597 England

Apr 27 '07 #9
Felix Kater wrote:
On Fri, 27 Apr 2007 13:23:31 +0100
Chris Dollin <ch**********@h p.comwrote:
>Sometimes, the "appropriat e conversion machinery" leaves the
underlying bit-pattern unchanged, leading to the illusion that the
cast means "Treat something as something else without change". But
this is an accident of implementation.

Some notes:

'sometimes': This is exactly what I mean--from a students view. Talking
about casts does not give you the clue if data is converted or not.
Excuse me, it does: the data is /always/ converted.

Sometimes the implementation of the conversion is trivial and preserves
the bit-pattern. Doesn't matter: the value has been converted.
'illusion': In practice it *is* a big difference if you can or cannot
cast something into somthing else and back again without having changed
a single byte.
Some conversions are lossless; some are not. Just because /sometimes/
the implementation doesn't have to do anything doesn't mean it always
won't.

If you stick to what the Standard guarantees, you won't write code
where your round-tripping is surprising.

I'd like examples of your "In practice it *is* a big difference".
So calling it an illusion wouldn't help.

'accident of implementation' : I wonder if there aren't cases in which
legal casts could simply never be 'conversions' nor make sense
as such in any implementation. So, this was reason why casts are ment
not to be conversions sometimes.
It's not the reason, because they're not sometimes-not-conversions.

--
"Possibly you're not recalling some of his previous plans." Zoe, /Firefly/

Hewlett-Packard Limited Cain Road, Bracknell, registered no:
registered office: Berks RG12 1HN 690597 England

Apr 27 '07 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
3597
by: Aaron W. West | last post by:
Fun with CAST! (Optimized SQLServerCentral script posts) I found some interesting "tricks" to convert binary to hexadecimal and back, which allow doing 4 or 8 at a time. Test code first: -- These two have the same output, other than the width: select dbo.ufn_vbintohexstr(0x123456789abcdef1234) select 0x123456789abcdef1234
4
10475
by: Ray | last post by:
When a single-bit bitfield that was formed from an enum is promoted/cast into an integer, does ANSI C say anything about whether that integer should be signed or unsigned? SGI IRIX cc thinks it is an unsigned integer, so I see a +1 if the bit is set. Microsoft VC++ thinks it's signed, so I see -1 if the bit is set. Ex. typedef enum {
17
2680
by: Hazz | last post by:
In this sample code of ownerdraw drawmode, why does the '(ComboBox) sender' line of code need to be there in this event handler? Isn't cboFont passed via the managed heap, not the stack, into this cboFont_DrawItem event handler? Why does it need to be cast? -hazz ,................. cboFont.Items.AddRange(FontFamily.Families); } private void cboFont_DrawItem(object sender,
5
3446
by: Nick Flandry | last post by:
I'm running into an Invalid Cast Exception on an ASP.NET application that runs fine in my development environment (Win2K server running IIS 5) and a test environment (also Win2K server running IIS 5), but fails on IIS 6 running on a Win2003 server. The web uses Pages derived from a custom class I wrote (which itself derives from Page) to provide some common functionality. The Page_Load handler the failing webpage starts out like this: ...
5
1270
by: zafar haider | last post by:
what are the specific meanings of word ".Net". what describes the word ".Net" why not something else please tell me the answer becuase it was asked in my interview
6
6732
by: Lore Leunoeg | last post by:
Hello I derived a class MyControl from the Control class. Public Class MyControl Inherits Control Sub New() MyBase.New() End Sub End Class
9
2729
by: Frederick Gotham | last post by:
Let's assume that we're working on the following system: CHAR_BIT == 8 sizeof( char* ) == 4 (i.e. 32-Bit) Furthermore, lets assume that the memory addresses are distributed as follows: 0x00000000 through 0xFFFFFFFE : Valid byte addresses
5
2367
by: Frederick Gotham | last post by:
Before I begin, here's a list of assumptions for this particular example: (1) unsigned int has no padding bits, and therefore no invalid bit- patterns or trap representations. (2) All types have the same alignment requirements. (3) sizeof(double) >= sizeof(unsigned) ===================================== We can cast from double to unsigned int as follows:
1
3266
by: Tim Couper | last post by:
As you know, when an IOError is raised, you get a helpful: <useful descriptor of the error> Is there a list of all possible values of N which can be returned, and their meanings? -- Dr Tim Couper CTO, SciVisum Ltd
0
9708
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9587
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10340
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10324
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
7623
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6857
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5527
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
3827
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2998
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.