Skip to content

Instantly share code, notes, and snippets.

@Voronar
Created January 20, 2022 10:40
Show Gist options
  • Save Voronar/c9999187c7fd5e9fccc73a1bf09dcced to your computer and use it in GitHub Desktop.
Save Voronar/c9999187c7fd5e9fccc73a1bf09dcced to your computer and use it in GitHub Desktop.
C/C++
#include <stdio.h>
#define TRY(a) ({ \
void* retval = NULL; \
if (a != NULL) { retval = a; } else { return retval; } \
retval; \
})
int sum(int _a, int _b) {
int a = TRY(_a);
int b = TRY(_b);
return a + b;
}
const char* concat(int _a, int _b) {
int a = TRY(_a);
int b = TRY(_b);
char *str = malloc(strlen(a) + strlen(b));
strcat(str, a);
strcat(str, b);
return str;
}
int main() {
printf("sum: %i\n", sum(2, 2));
printf("sum: %s\n", sum(2, NULL));
const char* s1 = concat("hello ", "world");
*s1 = "123";
printf("concat: %s\n", s1);
free(s1);
char* s2 = concat("hello ", NULL);
printf("concat: %s\n", s2);
free(s2);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment