Created
October 18, 2016 22:25
-
-
Save bethanylong/9fef09d80cd6fce5e2fc966865d4e2cf to your computer and use it in GitHub Desktop.
"Hello world" demo program for gdb talk
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 <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
const int BUFSIZE = 1024; | |
const int ARBITRARY_THRESHOLD = 3; | |
int is_uppercase(char ch) { | |
return ch >= 'A' && ch <= 'Z'; | |
} | |
int is_lowercase(char ch) { | |
return ch >= 'a' && ch <= 'z'; | |
} | |
char flip_case(char ch) { | |
/* If ch is an uppercase letter, return it in lowercase. | |
* If ch is a lowercase letter, return it in uppercase. | |
* Otherwise, return ch. */ | |
if (is_uppercase(ch)) { | |
return ch - 'A' + 'a'; | |
} else if (is_lowercase(ch)) { | |
return ch - 'a' + 'A'; | |
} else { | |
return ch; | |
} | |
} | |
char rot13(char ch) { | |
/* If ch is a letter, offset it by 13 (wrap back to start of alphabet | |
* if necessary). */ | |
int offset = 0; | |
if (is_uppercase(ch)) { | |
offset = 'A'; | |
} else if (is_lowercase(ch)) { | |
offset = 'a'; | |
} else { | |
return ch; | |
} | |
return (ch - offset + 13) % 26 + offset; | |
} | |
int main(int argc, char **argv) { | |
int intuitive_arg_count = argc - 1; | |
char *buf = (char *) malloc(BUFSIZE); // sizeof(char) is defined as 1 | |
snprintf(buf, BUFSIZE, | |
"Hello, world! I was called with %d argument%s.\n", | |
intuitive_arg_count, | |
(intuitive_arg_count) == 1 ? "" : "s"); | |
char (*fn)(char); // fn: pointer to function that takes and returns a char | |
if (intuitive_arg_count > ARBITRARY_THRESHOLD) { | |
fn = &flip_case; | |
} else { | |
fn = &rot13; | |
} | |
for (int i = 0; i < strlen(buf); i++) { | |
buf[i] = (*fn)(buf[i]); | |
} | |
printf("%s", buf); | |
free(buf); // Not strictly necessary since we're exiting, but hygenic | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment