[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Lies in education [was Re: The "loop and a half"]

Steve D'Aprano <steve+python at pearwood.info> writes:

> On Thu, 12 Oct 2017 02:43 am, Marko Rauhamaa wrote:
>> Chris Angelico <rosuav at gmail.com>:
>>> The places where C++ is not a superset of C are mostly things you
>>> wouldn't want to be doing anyway. You can generally take C code and
>>> compile it with a C++ compiler, and it'll have the same semantics.
>> Here's a C/C++ program:

It's not a C program in the sense that it's undefined in C.  A struct
with no members is a constraint violation.

>> ========================================================================
>> #include <stdio.h>
>> int main()
>> {
>>     struct {} s;
>>     printf("%d\n", (int) sizeof 'a');
>>     printf("%d\n", (int) sizeof s);
>>     return 0;
>> }
>> ========================================================================
>> When compiled (with gcc) as a C program, the output is:
>>     4
>>     0
>> When the same program is compiled (with gcc) as a C++ program, the
>> output is:
>>     1
>>     1
>> That is not immediately all that significant but points to subtle
>> incompatibilities between the data models of C and C++.
> I don't think anyone should expect that platform specific details like the
> size of a char should be precisely the same between C and C++. Even two
> different C compilers could return different values.

The size of (in the sense of sizeof) an expression of type char is
defined to be 1.  All conforming C and C++ compilers must return 1 in
such a case.  The difference being highlighted here is that, in C, 'a'
is an integer expression.  In C++ it's of type char.