473,698 Members | 2,841 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

translating C++ -> C

I am going to take the liberty of crossposting this to comp.lang.c++
(originally comp.lang.c), and to summarize the discussion for the sake
of those reading only c++.

The question is: If you are writing C and you have a struct P, can you
create a struct C that is an extension of the first (starts just like P
and adds some data), and then use a C* as if it were an P*?

Example:

typedef struct {
int a;
short b;
} P;

typedef struct {
int a;
short b;
long long c;
} C;

C *c; P *p;
c = (C*) malloc(sizeof(C ));
c->a = 1; c->b =2;
p = (P*) c;
printf("%d\n", p->a);
P and C stand for parent and child, and hint at the OO structure that we
are tying to mimick in C. We want to be able to use a child struct as a
parent struct, as you would in C++.

The basic answer in comp.lang.c is "it works on any compiler I have
seen, but there is no guarantee".

The standard appears to limit the freedom of the compiler in laying out
the struct: the order of the elements if fixed, padding can be added
between elements and at the end, but only if necessary for alignment.
This does not quite prescribe where the padding should be. If you have
three byte-aligned bytes, and a 4-byte aligned 4-byte word, you need one
byte of padding, but you can put that whereever you want before the
word: bbbpwwww or bpbbwwww are both allowed (b is a byte, p padding, and
w part of the word). The standard apperently does not require that the
padding is applied the same way in different structs.

Another problem that has been pointed out is this: what if P ends in a
4-byte aligned byte b and 3 bytes of padding. The compiler may decide
that the most efficient way to clear b is to do a four-byte clear
operation. If C adds 3 bytes to the struct, these may go in the
padding, and an attempt to assign p.b=0 may clear the extra the extra
bytes in C if p points to a C struct.

Now the reason to crosspost to comp.lang.c++: I think the c++ to c
translator used overlapping for inheritance, so the c++ people must be
experts. Am I correct? Does that mean that the translator depended on
features of the compilers that are not prescribed by the standard, or am
I missing something?

It is clear that there are alternatives, e.g., we may define C as
typedef struct {
P p;
long c;
} C;
at the expense of some extra typing when accessing common elements.

[disclaimer: I do not have the C standard. Everyting I write about it
is either hearsay or Harbison & Steele.]

Roderick
Jul 23 '05 #1
2 1425
Roderick Bloem <ro************ @ist.tu-graz.ac.at> writes:
[...]
The standard appears to limit the freedom of the compiler in laying
out the struct: the order of the elements if fixed, padding can be
added between elements and at the end, but only if necessary for
alignment.
C99 6.7.2.1p13:
Within a structure object, the non-bit-field members and the units
in which bit-fields reside have addresses that increase in the
order in which they are declared. A pointer to a structure object,
suitably converted, points to its initial member (or if that
member is a bit-field, then to the unit in which it resides), and
vice versa. There may be unnamed padding within a structure
object, but not at its beginning.

C99 6.7.2.1p15:
There may be unnamed padding at the end of a structure or union.

There is no implication that padding can be added only if necessary
for alignment. The compiler is free to insert padding because it
makes the struct look bigger and scares away predators.

[...]
Now the reason to crosspost to comp.lang.c++: I think the c++ to c
translator used overlapping for inheritance, so the c++ people must be
experts. Am I correct? Does that mean that the translator depended
on features of the compilers that are not prescribed by the standard,
or am I missing something?


Are you referring to cfront?

It probably means that the author(s) of the translator either were
experts on C, or were lucky enough not to run into any problems. It
doesn't imply anything about the C expertise of C++ programmers other
than the ones who worked on the translator.

There's no fundamental reason why either the translator or the code it
generated had to be written in perfectly portable C. As long as it
did the job, that may have been good enough, and the authors were free
to take advantage of assumptions that happen to be valid for all C
implementations of interest, even if they're not guaranteed by the
standard. (Portable standard-conforming code is generally better, all
else being equal, but all else is not always equal.)

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Jul 23 '05 #2
In article <42************ ***********@aco news.univie.ac. at>
Roderick Bloem <ro************ @ist.tu-graz.ac.at> wrote:
Now the reason to crosspost to comp.lang.c++: I think the c++ to c
translator used overlapping for inheritance, so the c++ people must be
experts. Am I correct?
On the first, perhaps; on the second, well... :-)
Does that mean that the translator depended on features of the
compilers that are not prescribed by the standard ...


If you are referring to cfront, it *definitely* *did* depend on
non-portable features. In particular, you had to tell it all about
how the C compiler it used as its "assembler" laid out structures,
including padding, so that it could track the C compiler's work
and subvert it.

Note that cfront was in fact a "real compiler" according to the
definition I prefer:

To decide if Step S is a "preprocess or" or a "compiler",
answer the following question: if an error occurs *after*
Step S, is it a mistake by the programmer, or is it a
mistake in Step S?

Consider the following examples:

foo.c, line 123: invalid operand to unary &
# or same with "foo.cpp" as the file name

/tmp/151522.c, line 123: invalid operand to unary &

/tmp/151523.s, line 5012: invalid register operand to add

When compiling a C or C++ program named "foo.c" or "foo.cpp", the
first message is perfectly natural if you goofed up some "#define",
because the preprocessor part of the language does not understand
the language proper. But getting (just) the second message from
a C++ compiler, when compiling "foo.cpp", indicates a bug in the
C++ compiler, not invalid C++ code that was simply copied through
to the C compiler. So C++ is not a "preprocess or", because it is
a bug in the C++ system, not a bug in your own code, that produced
the message about file in /tmp.

In all cases, the last message (from the assembler) indicates a
bug in the compiler, because the compiler should not be emitting
invalid CPU register names. The exception to this rule occurs if
the compiler happens to have an "insert arbitrary assembly code"
escape clause (like __asm__), and you used it.
--
In-Real-Life: Chris Torek, Wind River Systems
Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W) +1 801 277 2603
email: forget about it http://web.torek.net/torek/index.html
Reading email is like searching for food in the garbage, thanks to spammers.
Jul 23 '05 #3

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

Similar topics

6
1551
by: Davis Marques | last post by:
hi; I'm translating some PHP scripts to Python and have hit a roadblock with a for statement. If someone could explain to me how one should translate the multiple increment, evaluations, etc. in the first line I would appreciate it deeply ... for ($y = 0, $x = $cx-$cy-1; $y <= $cy; ++$y,++$x) { $prd = $q * $y_ar + $car; $prd -= ($car = intval($prd / 1E7)) * 1E7;
2
1444
by: Henrik S. Hansen | last post by:
How do you best go about translating characters like '\\n' to '\n'? This is for a configuration file parser, where the "backslash convention" is supported. The naive approach -- re.sub('\\\\(.)', '\\\1', s) -- doesn't work, of course. The best I've come up with so far is a special case for every character to be translated. There must be an easier way? -- Henrik S. Hansen http://freecode.dk/~hsh/
1
2041
by: Michael Friendly | last post by:
I have a LaTeX document describing a long list of items that I want to translate to XML to treat these as a database. I've written a perl script to do the basic translation, and a basic DTD file, but I am stumped at translating LaTeX character encodings to something XML won't choke on. I found GNU recode to solve most of this, using cat milestone.tex | recode -d tex..xml | itemdb -s xml -o milestone.xml
12
1648
by: Charles Law | last post by:
Hi guys A bit of curve ball here ... I have a document (Word) that contains a series of instructions in sections and subsections (and sub-subsections). There are 350 pages of them. I need to translate these instructions into something that can be processed automatically, so I have used the Command pattern to set up a set of commands that correspond to the various instructions in the document.
23
3142
by: gregf | last post by:
I have a paragraph of text pasted into a word document, it's in Polish, complete with polish characters. They show up just fine in word, but the program I use for web page programming, HomeSite, won't translate it. When I paste the text into the code, the special characters are missing. If they would show up there I could use the Replace Special Characters feature to change it to the proper code, but it won't even paste into it...
0
1117
by: Dylan Phillips | last post by:
I'm interested in how other participants in this new group are implementing SQL Full-Text Search on their Web Sites. How are you translating the user search string: "DirectX managed code" into the contains statement syntax ' "DirectX" AND "managed" AND "code" '? I started writing a query parsers as an intermediary to handle control characters like , but frankly it's becoming a rather pain in the a$$. If anyone has any suggestions as...
1
1085
by: J | last post by:
Hi all, I just finished a asp.net project, which is based on English language, and all of sudden, client need different language also, say German, Chinese, etc. So, what is the best way, or I should say easiest way for me to do all the translating? Thanks in advance.
6
2532
by: Jumping Matt Flash | last post by:
The code i'm writing is using VB .NET and is for a web service returning a dataset, which is in turn to be used by an ASP .NET application displaying a datagrid. I'm currently populating a datagrid using a "select top 1 column 1, column2, column3 from tblTable" statement. As there will only ever be one row returned I want to be able to to switch the column names to be row1 and the column values to be row 2 i.e. select house, street,...
2
1634
by: kimi | last post by:
Voip Learning and Translating Tutorial Voice Over IP is a new communication means that let you telephone with Internet at almost null cost. How this is possible, what systems are used, what is the standard, all that is covered by this Howto. http://www.freewebs.com/voipformula/VoIP-HOWTO.html
1
1863
by: timn | last post by:
Translating Access SQL queries into SQL subqueries. -------------------------------------------------------------------------------- I have a query in Access that uses a subquery, I would like some help on translating it into SQL as a subquery so I can use it in an application. the queries in Access are the subquery... (query4) SELECT Movement.DateTime, Movement.StudentID, Movement.Subject, Movement.Teacher, Movement.Destination,...
0
8683
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
8609
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
9170
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9031
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
8901
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,...
0
5862
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
4371
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...
0
4622
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2007
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.