On 2/19/18 10:35 AM, Chris Angelico wrote:
On Tue, Feb 20, 2018 at 12:34 AM, Steven D'Aprano
<steve+comp.lang.pyt...@pearwood.info> wrote:
On Mon, 19 Feb 2018 20:14:32 +1100, Chris Angelico wrote:

As an integer, 3.141590 is 1078530000 $

Looks to me like C is perfectly happy to interpret a float as an int.
Yes, but that's not an *automatic* coercion. To count as weakly typed,
the compiler has to do it automatically, without an explicit cast or
Fair enough. If you ignore warnings, then C does have that kind of weak typing:

$ cat demo.c
#include <stdio.h>

int main() {
     float f = 3.14159;
     int *i = &f;
     printf("As an integer, %f is %d\n", f, *i);
     return 0;

$ gcc demo.c
demo.c: In function ‘main’:
demo.c:5:14: warning: initialization from incompatible pointer type
      int *i = &f;

GCC was quite happy to compile that code, even though the type of "&f"
is "pointer to float", and it's being assigned to a variable of type
"pointer to int". But C is a language saddled with so much history and
backward compatibility constraints that there are some things you just
CAN'T make into errors; so in terms of "how safe is C?", I'd have to
say that warnings (especially those that are enabled by default - I
didn't need to say "-Wall" for this test), count as "disallowing",
especially if all the major compilers emit warnings on the same code.
But I do see the argument that "it compiles, so the language clearly
permits it".


One thing to note, that is more an issue with GCC than with C. By the standard, that is a constraint violation, that requires a diagnostic, and the C standard says it provides no definition of what should happen here, which is about as strong as it gets to defining something as an 'Error', the only thing with a stronger requirement is the #error statement which must not running the program.

GCC has decided that this diagnostic will be considered just a 'Warning' and provides its own meaning to the statement. You really want to run with pedantic-errors enabled to get GCC to reject code with constraint violations.

Richard Damon


Reply via email to