C as portable assembler
C as portable assembler
Posted May 31, 2011 17:56 UTC (Tue) by anton (subscriber, #25547)In reply to: C as portable assembler by khim
Parent article: What Every C Programmer Should Know About Undefined Behavior #3/3
Why people accept that i = i++ + ++i; is unsafe and unpredictable code
- Who would write "i = i++ + ++i;" anyway?
- It is easy to write what you intended here (whatever that was) in a way that's similarly short and fast and generates a similar amount of code.
but lots of other cases which trigger undefined behavior are perceived as safe?Because they were safe, until the gcc maintainers decided to break them (and the LLVM maintainers follow them like lemmings).
Posted Jun 1, 2011 9:16 UTC (Wed)
by khim (subscriber, #9252)
[Link]
It's easy to do in other cases, too. You can always use memcpy to copy from float to int. GCC will eliminate memcpy and unneeded variables. $ cat test.c They were never completely safe albeit cases where they break were rare. Today it happens more often. This is not the end of the world, but this is what you must know and accept.
That's the point...
It is easy to write what you intended here (whatever that was) in a way that's similarly short and fast and generates a similar amount of code.
#include <string.h>
int convert_float_to_int(float f) {
int i;
memcpy(&i, &f, sizeof(float));
return i;
}
$ gcc -O2 -S test.c
$ cat test.s
.file "test.c"
.text
.p2align 4,,15
.globl convert_float_to_int
.type convert_float_to_int, @function
convert_float_to_int:
.LFB22:
.cfi_startproc
movss %xmm0, -4(%rsp)
movl -4(%rsp), %eax
ret
.cfi_endproc
.LFE22:
.size convert_float_to_int, .-convert_float_to_int
.ident "GCC: (Ubuntu 4.4.3-4ubuntu5) 4.4.3"
.section
.note.GNU-stack,"",@progbits
Because they were safe, until the gcc maintainers decided to break them (and the LLVM maintainers follow them like lemmings).