Created
June 2, 2014 14:41
-
-
Save syphoxy/dcc291b543c4a0b14474 to your computer and use it in GitHub Desktop.
experimental object creation and validation in C
This file contains 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 <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