$ zig version
0.13.0
I have a program where at one point I intend to compare a c_short
value (stored in a struct) to a c_int
value imported from C standard library. Running the code in a debugger shows that both have value 1, but when I do a comparison of whether the values are equal (using ==
) it evaluates to false. I already tried casting the c_short
into c_int
before the comparison (using @as(c_int, my_short)
) but that didn’t help either. What am I doing wrong?
The program (call it poll.zig
):
const std = @import("std");
const c = @cImport({
@cInclude("poll.h");
});
pub fn main() void {
const watchable = c.struct_pollfd{
.fd = 0, // STDIN
.events = c.POLLIN,
};
var watchables: [1]c.struct_pollfd = .{ watchable };
const timeout: c_int = 0;
while (true) {
const events_count: c_int = c.poll(&watchables, watchables.len, timeout);
const something_happened: bool = events_count > 0;
const new_data_readable: bool = watchable.revents == c.POLLIN;
if (
something_happened
and new_data_readable
) {
std.log.info("There's data to be read from STDIN!");
}
}
}
The comparison I’m talking about occurs on line 18 (where we assign const new_data_readable: bool
).
Similar comparison works fine in the following C program (call it poc.c
). See line 21 where we assign int new_data_readable
:
#include <poll.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#define FD_READABLE 0
int main() {
struct pollfd fds_to_watch;
memset(&fds_to_watch, 0, sizeof(fds_to_watch));
fds_to_watch.events = POLLIN;
fds_to_watch.fd = FD_READABLE;
char buf[64] = {0};
while (1) {
int events = poll(&fds_to_watch, 1, 0);
int something_happened = events > 0;
int new_data_readable = fds_to_watch.revents & POLLIN;
if (
something_happened
&& new_data_readable
) {
int bytes_read = read(FD_READABLE, &buf, sizeof(buf));
printf("Read %d bytes from standard input\n", bytes_read);
}
}
}