Created
October 18, 2016 08:32
-
-
Save f0rki/9b2c2b73d46ccdad2b39ab79b3a5517f to your computer and use it in GitHub Desktop.
using something like rust Result in C?
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Coming from swift and hacking in a bit of C lately, I was looking for something like this, thanks!