Thanks to visit codestin.com
Credit goes to github.com

Skip to content

translate-c: C code that uses string literals as non-const char * #9126

@ehaas

Description

@ehaas

In C string literals have the type char[N] (not const, but modifying the contents is undefined behavior). C code that uses this isn't compatible with Zig's []const u8 string literals:

int main(void) {
   char *foo = "foo";
   return 0;
}
pub export fn main() c_int {
    var foo: [*c]u8 = "foo";
    return 0;
}
./test.zig:3:23: error: expected type '[*c]u8', found '*const [3:0]u8'
    var foo: [*c]u8 = "foo";
                      ^
./test.zig:3:23: note: cast discards const qualifier
    var foo: [*c]u8 = "foo";

This can occur in variable declarations, function calls, and struct and array initializers - did I miss any?

I noticed in getExprQualType we turn char * into const char * but I'm not sure why or what the implications of removing that are. Another solution would be to detect situations where a string literal is used as a char * and insert intToPtr / ptrToInt to cast away the constness.

Metadata

Metadata

Assignees

No one assigned

    Labels

    translate-cC to Zig source translation feature (@cImport)

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions