Skip to content

Incorrect output when translating function-scope static variable #929

Description

@lynae99

c2go incorrectly translates a function-scope static variable into an ordinary Go local variable.
In C, a function-scope static variable is initialized only once and preserves its value across function calls. However, the generated Go code declares the variable inside the function body, so it is reinitialized every time the function is called.
To Reproduce

#include <stdio.h>

void f(void) {
    static int x = 0;
    x++;
    printf("%d\n", x);
}

int main(void) {
    f();
    f();
    return 0;
}

Generated Go Code

func f() {
        var x int32 = int32(0)
        x += 1
        noarch.Printf((&[]byte("%d\n\x00")[0]), x)
}

func main() {
        f()
        f()
        return
}

Observed Behavior
The original C program prints:

1
2

The generated Go program prints:

1
1

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions