Path: utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!uunet!microsoft!jimad From: jimad@microsoft.UUCP (Jim ADCOCK) Newsgroups: comp.lang.c++ Subject: Re: Pointer conversion macro brainteaser Message-ID: <56042@microsoft.UUCP> Date: 24 Jul 90 18:32:51 GMT References: <43645@cornell.UUCP> Reply-To: jimad@microsoft.UUCP (Jim ADCOCK) Distribution: comp Organization: Microsoft Corp., Redmond WA Lines: 39 In article <43645@cornell.UUCP> peierls@cs.cornell.edu (Tim Peierls) writes: |The question is, for all you spec hackers, under what conditions is |this macro guaranteed by E&S to work? By "conditions" I mean nasty |things like implementation defined behavior, and by "work" I mean conform |to the description below in some useful if not rigorous way. | |#define bp2dp(B,D,p) ((p)?((D*)(((char*)(p))+1-((size_t)(B*)(D*)(void*)1))):0) If a coding trick uses any constructs considered by E&S to be "implementation dependent," then any "guarantees" from E&S are off. I don't have an E&S in front of me at the moment, but here's a short list of a few of the implementation dependencies I believe I see in this macro: * cast of small integer to void* * cast back of void* to something different than originally cast to void* * cast of B* to size_t * cast of B* to char* * use of odd address for structure pointer * cast of char* to D* |It works for cfront 2.0 and probably everywhere else. I disagree with both the first part and the second part of this statement. When I tried this macro on a cfront 2.0 derivative with B a virtual base class of D, the code compiled silently, then crashed at runtime. The reason it crashed was that in the case of a virtual base class, a D instance contains a pointer to the virtual base class B instance. Casting from D* to B* requires an actual evaluation of the pointer -- which resides in the hypothetical structure residing at address "1" Since the cfront implementation of virtual base classes seems reasonable [assuming one feels virtual base classes are reasonable :-] it follows that this macro will probably fail everywhere else too. |A reasonable translator or compiler should have no problem turning the entire |expression into a compare and a subtract. Again, not true if a class uses a virtual base.