3 ms·
The type system of C is not as good as some later ones, but it's perfectly sufficient to prevent errors of the type shown in TFA. struct user_id { uint64_t v
by colonwqbang 4y ago
The type system of C is not as good as some later ones, but it's perfectly sufficient to prevent errors of the type shown in TFA.
struct user_id { uint64_t val; };
void ban_user(struct user_id id);
- nivertech 4y agoyes, here's the correct code: #include <stdio.h> #include <stdint.h> typedef struct user_id { uint64_t val; } user_id_t; void ban_user(user_id_t id) { printf("user with id %lu was banned", id.val); } int main() { user_id_t someUser = {123}; ban_user(someUser); return 0; } output: > clang-7 -pthread -lm -o main main.c > ./main user with id 123 was banned And here's the code with the bug: #include <stdio.h> #include <stdint.h> typedef struct user_id { uint64_t val; } user_id_t; typedef struct group_id { uint64_t val; } group_id_t; void ban_user(user_id_t id) { printf("user with id %lu was banned", id.val); } int main() { user_id_t someUser = {123}; ban_user(someUser); group_id_t someGroup = {456}; ban_user(someGroup); return 0; } Compiler output: > clang-7 -pthread -lm -o main main.c main.c:22:12: error: passing 'group_id_t' (aka 'struct group_id') to parameter of incompatible type 'user_id_t' (aka 'struct user_id') ban_user(someGroup); ^~~~~~~~~ main.c:13:25: note: passing argument to parameter 'id' here void ban_user(user_id_t id) { ^ 1 error generated. exit status 1