Live data from Hacker News

Branch-free FizzBuzz in Assembly

pepijndevos.nl

1–10 of 47 posts

Re: Branch-free FizzBuzz in Assembly

#4
This is equivalent code in C if anyone is interested.

  #include 
  #include 

  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!

Re: Branch-free FizzBuzz in Assembly

#6

int ret int ret ret call call call int jmp No conditional branches. As long as you ignore what happens on the other side of those int instructions! Especially that last one...

Care to elaborate? Isn't `jmp` just a non-conditional jump? How is that branching?

Re: Branch-free FizzBuzz in Assembly

#8
post #6

int ret int ret ret call call call int jmp No conditional branches. As long as you ignore what happens on the other side of those int instructions! Especially that last one...

Care to elaborate? Isn't `jmp` just a non-conditional jump? How is that branching?

Branch and jump are synonyms in this context.

Re: Branch-free FizzBuzz in Assembly

#9
post #8
post #6

Earlier quoted context omitted.

Care to elaborate? Isn't `jmp` just a non-conditional jump? How is that branching?

Branch and jump are synonyms in this context.

Oh cool! I always thought of a branch as a conditional jump - I guess I was wrong. It appears that even unconditional branches are still branches!

"A branch is an instruction in a computer program that may, when executed by a computer, cause the computer to begin execution of a different instruction sequence. Branch (or branching, branched) may also refer to the act of beginning execution of a different instruction sequence due to executing a branch instruction. A branch instruction can be either an unconditional branch, which always results in branching, or a conditional branch, which may or may not cause branching depending on some condition."

Re: Branch-free FizzBuzz in Assembly

#10
post #4

This is equivalent code in C if anyone is interested. #include #include 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 branch…

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