Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

This is equivalent code in C if anyone is interested.

  #include <stdio.h>
  #include <stdlib.h>

  const char* table[] = { "%d\n" , "Fizz\n" , "Buzz\n" , "FizzBuzz\n" } ;

  void E( int i )
	{
	    exit( 0 ) ;
	}

  void F( int i )
	{
	        size_t c = !( i%3 ) + !( i%5 )*2 ;
		printf( table[c] , i ) ;
	}

  void ( *func[2] )( int ) = { F , E } ;

  int main( void )
	{
		int p = 1 ;
		while( 1 )
		{
			func[p/102]( p++ ) ;
		}

		return 0 ;
	}
This of course only avoids conditional branches.

EDIT: I just noticed I have undefined behavior in my code.

Bonus internet points for the first one to point it out!



"Unsequenced modification and access to 'p'" for:

    func[p/102]( p++ ) ;
A quick search brought me to http://www.bionoren.com/blog/2013/07/unsequenced-modificatio... : 'Basically, the compiler is free to reorder anything and everything until it hits a “sequence point”. Things like return, if, assignment, variable declaration, etc are all sequence points.'

In the parent code sample, it seems the compiler is free to execute "p++" before the "p/102" since there is no sequence point between them.

I was previously unaware of this undefined behavior. Thanks for this, rertrree!


Have you looked at the generated ASM? I suspect printf contains a lot of branches. But then so might those syscalls I guess.


Yes.

Library calls will have conditionals, but apart from that there are none.




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

Search: