Wednesday, 11 September 2013

golang: confusing output on fizzbuzz with switch case statement

golang: confusing output on fizzbuzz with switch case statement

Here the famous "fizz buzz" program in Go using switch/case and if/else
conditionals. The problem is that using switch/case is generating
unexpected output while if/else (with same conditions) works fine. I know
that switch/case in golang is different than other C-family languages, but
what's wrong with this code fragment?
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)
}
}

No comments:

Post a Comment