Skip to content

Instantly share code, notes, and snippets.

@wilyJ80
Last active April 3, 2025 13:13
Show Gist options
  • Save wilyJ80/3739aad52d897c5586ed740589f8e760 to your computer and use it in GitHub Desktop.
Save wilyJ80/3739aad52d897c5586ed740589f8e760 to your computer and use it in GitHub Desktop.
Half adder (CLI args)
#include <stdio.h>
#include <stdlib.h>
#include "./utils.h"
int main(int argc, char** argv) {
if (argc != 3) {
fprintf(stderr, "Error: expected 2 args (numbers)\n");
exit(EXIT_FAILURE);
}
/* for each arg */
for (char** arg = argv + 1; arg < argv + 3; arg++) {
/* for each arg char */
for (char* c = *arg; *c != '\0'; c++) {
if (!(*c == '0' || *c == '1')) {
fprintf(stderr, "Error: invalid input: not integers 0 or 1\n");
exit(EXIT_FAILURE);
}
}
}
struct Inputs inputs = {
.a = strtol(argv[1], NULL, 10),
.b = strtol(argv[2], NULL, 10)
};
struct Calculator calculator = {
.sum = inputs.a ^ inputs.b,
.carry = inputs.a && inputs.b,
};
printf("Sum: %d,\nCarry: %d\n", calculator.sum, calculator.carry);
return EXIT_SUCCESS;
}
#ifndef INPUTS_H
#define INPUTS_H
struct Inputs {
int a;
int b;
};
struct Calculator {
int sum;
int carry;
};
#endif // !INPUTS_H
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment