I'm trying to port the following C code to Go:
if (x == 0 || x-- == 0) {
// Stuff
}
This isn't legal in Go because I can't modify x
inside the check clause.
What's a good way of representing this in Go without e.g. duplicating the contents of the block?
If x--
is a typo and should be --x
, then I would make the changes to x
explicit:
if x == 0 || x == 1 {
x = 0
// Stuff
} else {
x--
}
Otherwise, your C code has a bug. If x == 0
is false, then x-- == 0
will also be false because you're using the post-increment operator. Therefore, the code would be equivalent to:
if (x == 0) {
// Stuff
} else {
x--;
}
The Go code
if x != 0 {
x--
} else {
// Stuff
}
is equivalent to the C code
if (x == 0 || x-- == 0) {
// Stuff
}
For example, in Go,
package main
import (
"fmt"
)
func main() {
for _, x := range []int{-42, -2, -1, 0, 1, 2, 42} {
fmt.Printf("x %d:", x)
if x != 0 {
x--
} else {
fmt.Printf(" Stuff %d:", x)
}
fmt.Printf(" x %d:
", x)
}
}
Output:
x -42: x -43:
x -2: x -3:
x -1: x -2:
x 0: Stuff 0: x 0:
x 1: x 0:
x 2: x 1:
x 42: x 41:
For example, in C,
#include <stdio.h>
int main() {
int a[] = {-42,-2,-1,0,1,2,42};
for (int i = 0; i < (sizeof a)/sizeof a[0]; i++) {
int x = a[i];
printf("x %d:", x);
if (x == 0 || x-- == 0) {
printf(" Stuff %d:", x);
}
printf(" x %d:
", x);
}
}
Output:
x -42: x -43:
x -2: x -3:
x -1: x -2:
x 0: Stuff 0: x 0:
x 1: x 0:
x 2: x 1:
x 42: x 41: