Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Translate-C doesn't understand that bool is a one-bit unsigned integer #22923

Open
drfuchs opened this issue Feb 17, 2025 · 0 comments
Open

Translate-C doesn't understand that bool is a one-bit unsigned integer #22923

drfuchs opened this issue Feb 17, 2025 · 0 comments
Labels
bug Observed behavior contradicts documented or intended behavior translate-c C to Zig source translation feature (@cImport)

Comments

@drfuchs
Copy link

drfuchs commented Feb 17, 2025

Zig Version

0.14.0-dev.2851+b074fb7dd

Steps to Reproduce and Observed Behavior

In the C standard, the "bool" type is specified to be a one-bit, unsigned integer, and boolean constants "true" and "false" are specified to be one and zero, respectively. Thus, a bool variable or constant can be used as an array subscript, and can be cast to and from other integer types.

So, this C program is well defined, and compiles and runs warning- and error-free:

#include <stdbool.h>

const char* boolname(bool b)
{
  static const char* names[2] = {"False", "True"};
  return names[b];
}

#include <stdio.h>
int main(void)
{
  printf("BooleanNames: %s %s\n", boolname(false), boolname(true));

  for (int int1 = false; int1 <= true; int1++)
    for (int int2 = false; int2 <= true; int2++)
      {
        const bool bool1 = (bool)int1; const bool bool2 = (bool)int2;
        const char rel = (bool1 < bool2) ? '<' : (bool1 > bool2) ? '>' : '=';
        printf("%s %c %s\n", boolname(bool1), rel, boolname(bool2));
      }

  return 0;
}

But translate-c produces zig code that fails to compile:

boolbug.zig:67:25: error: expected type 'usize', found 'bool'
    return names.static[b];
                        ^
boolbug.zig:340:47: error: expected type 'bool', found 'c_int'
                const bool1: bool = @as(bool, int1);
                                              ^~~~

Expected Behavior

Resulting zig code should compile and run, producing:

BooleanNames: False True
False = False
False < True
True > False
True = True
@drfuchs drfuchs added the bug Observed behavior contradicts documented or intended behavior label Feb 17, 2025
@alexrp alexrp added the translate-c C to Zig source translation feature (@cImport) label Feb 17, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Observed behavior contradicts documented or intended behavior translate-c C to Zig source translation feature (@cImport)
Projects
None yet
Development

No branches or pull requests

2 participants