Hacker News new | past | comments | ask | show | jobs | submit login

http://pastebin.com/2fGefex4

  $ gcc -o addalot --std=c99 -Os addalot.c
  $ ./addalot
  [1500117.315354] 0.000032 per iteration on average.
Works fine for me.



This is not the correct C program, this is a C program for the compiler with tail call optimization (or with the stack large enough for it to work). There's no TCO in the C standard.


There is no restriction against TCO in the C standard either. TCO is a valid optimization for a compiler to apply. So what is incorrect about it?


Because it relies on the particular implementation of C compiler, not on the C standard. Take -Os flag away or use a compiler that doesn't have TCO, and the program has a bug.

See also:

* using memcpy() for overlapping regions (relies on the particular implementation of memcpy(); was exposed by a change in glibc - http://lwn.net/Articles/414467/);

* memory aliasing assumptions;

* passing NULL, 0 to memcpy() (http://code.google.com/p/spiped/source/detail?r=8);

etc.


It is ansi C standard code. There is an implementation limitation (stack size) that this program runs into. However that doesn't violate the C standard in any way, because the standard doesn't specify available stack space.

So the program is compatible with certain C implementations in certain configurations. Given the C standard allows a C implementation to pick any stack size they like (including zero) we could claim that about all valid C programs that make any use of the stack.


> There's no TCO in the C standard. That doesn't make tail-recursive C programs any less correct.


They're not incorrect, but that's mostly because the C standard also allows you to assume an infinite stack, so recursive programs that ask for absurd stack depths don't violate the standard with or without TCO. But if in practice the program only runs successfully when compiled on a compiler with TCO, it's not very portable, in that it relies on non-guaranteed compiler features for it to actually work.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: