Branch-free FizzBuzz in Assembly
pepijndevos.nl
Branch-free FizzBuzz in Assembly
1–10 of 47 posts
Re: Branch-free FizzBuzz in Assembly
#2Re: Branch-free FizzBuzz in Assembly
#3 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...Re: Branch-free FizzBuzz in Assembly
#4 #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
#5Re: Branch-free FizzBuzz in Assembly
#6int 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...
Re: Branch-free FizzBuzz in Assembly
#7int 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...
Re: Branch-free FizzBuzz in Assembly
#8int 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
#9Earlier 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.
"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
#10This 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…