Scaring fizzbuzz output with case case statement

Here is Go's famous fizz buzz program using switch / case and if / else conditions. The problem is that using switch / case creates unexpected output, and if / else (with the same conditions) works fine. I know that switch / case in golang is different from other C-family languages, but what is wrong with this piece of code?

func main() { const ( FIZZ = 3 BUZZ = 5 ) //section with switch/case gives unexpected output for i := 1; i <= 30; i++ { switch { case i % FIZZ == 0: fmt.Printf("%d fizz\t", i%3) fallthrough case i % BUZZ == 0: fmt.Printf("%d buzz\t", i%5) } fmt.Printf("\t%d\n", i) } fmt.Printf("now towards the if/else\n") //section with if/else works as expected for i := 1; i <= 30; i++ { if i % FIZZ == 0 { fmt.Printf("%d fizz\t", i%3) } if i % BUZZ == 0 { fmt.Printf("%d buzz\t", i%5) } fmt.Printf("\t%d\n", i) } 

}

+4
source share
2 answers

From golang spec :

Passage Applications

The failure operator transfers control to the first statement of the following case in the switch statement. This can only be used as the final non-empty instruction in such a section.

So, the problem is this: "case i% FIZZ == 0" has a failure at the end, so "case i% BUZZ == 0" also holds, but the condition "i% BUZZ == 0" is also not checked.

So, to implement Fizz Buzz in golang using the switch, you need to remove the failure and add another case branch to the beginning: play.golang.org . As you can see, the if-version is more concise.

+6
source

You can use i%15 for fizzbuzz . This option gives a performance gain. One number - one division and one system call (sys_write). And don't worry about fallthrough . Play

 func main() { const ( FIZZ = 3 BUZZ = 5 FIZZBUZZ = 15 ) for i := 1; i <= 30; i++ { switch { case i % FIZZBUZZ == 0: fmt.Printf("%d fizzbuzz\n", i) case i % FIZZ == 0: fmt.Printf("%d fizz\n", i) case i % BUZZ == 0: fmt.Printf("%d buzz\n", i) default: fmt.Printf("%d\n", i) } } } 
+2
source

Source: https://habr.com/ru/post/1501665/


All Articles