Skip to content

Instantly share code, notes, and snippets.

@syphoxy
Created June 2, 2014 14:41
Show Gist options
  • Save syphoxy/dcc291b543c4a0b14474 to your computer and use it in GitHub Desktop.
Save syphoxy/dcc291b543c4a0b14474 to your computer and use it in GitHub Desktop.
experimental object creation and validation in C
#include <stdlib.h>
#include <stdio.h>
#define PERSON_NAME_UNSET 0x0001
#define PERSON_GROUPS_UNSET 0x0002
typedef struct collection_t {
void **items;
int count;
int available;
} collection_t;
typedef struct person_t {
char *name;
int birthday;
int _errors;
collection_t *groups;
} person_t;
int
person_validate(person_t *person)
{
person->_errors = 0;
if (person->name == NULL) {
person->_errors |= PERSON_NAME_UNSET;
}
if (person->groups == NULL) {
person->_errors |= PERSON_GROUPS_UNSET;
}
return person->_errors == 0;
}
int
main(int agrc, char **argv)
{
person_t *person = malloc(sizeof (person_t *));
if (person_validate(person)) {
printf("%s is a valid person object!\n", person->name);
} else {
if (person->_errors & PERSON_NAME_UNSET) {
person->name = "";
}
if (person->_errors & PERSON_GROUPS_UNSET) {
person->groups = (collection_t *)malloc(sizeof (collection_t *));
}
if (person_validate(person)) {
puts("Validation passed with defaults!");
} else {
puts("Validation failed with defaults!");
}
}
return EXIT_SUCCESS;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment