Skip to content

Instantly share code, notes, and snippets.

@f0rki
Created October 18, 2016 08:32
Show Gist options
  • Save f0rki/9b2c2b73d46ccdad2b39ab79b3a5517f to your computer and use it in GitHub Desktop.
Save f0rki/9b2c2b73d46ccdad2b39ab79b3a5517f to your computer and use it in GitHub Desktop.
using something like rust Result in C?
#include <stdbool.h>
#include <stdio.h>
#define DEFINE_RESULT(T, E, NAME) \
typedef struct { \
bool success : 1; \
union { \
T result; \
E error; \
}; \
} NAME;
DEFINE_RESULT(int, int, Result)
Result func_1(int x) {
Result r = { success: true, result: 0 };
if (x >= 0) {
r.result = x * 2;
} else {
r.success = false;
r.error = 1;
}
return r;
}
int func_2(int x, int* res) {
if (x >= 0) {
*res = x * 2;
return 0;
} else {
return 1;
}
}
int main() {
Result r;
int x;
int e;
for (int i = -1; i < 2; ++i) {
r = func_1(i);
if (r.success) {
printf("result is %d\n", r.result);
} else {
switch (r.error) {
// ...
default:
printf("error set to %d\n", r.error);
}
}
}
for (int i = -1; i < 2; ++i) {
e = func_2(i, &x);
if (e == 0) {
printf("result is %d\n", x);
} else {
switch (e) {
// ...
default:
printf("error set to %d\n", e);
}
}
}
return 0;
}
@cellularmitosis
Copy link

Coming from swift and hacking in a bit of C lately, I was looking for something like this, thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment