Skip to content

Instantly share code, notes, and snippets.

@remram44
Last active February 23, 2020 16:02
Show Gist options
  • Save remram44/43da80a2b3c8745a3d29e48a5e5748a0 to your computer and use it in GitHub Desktop.
Save remram44/43da80a2b3c8745a3d29e48a5e5748a0 to your computer and use it in GitHub Desktop.
*~
01-orig
02-global
03-struct
#include <stdio.h>
/* First version: this does everything in a single call to count_to() */
void count_to(int target) {
int i;
/* using a loop */
for(i = 1; i <= target; i++) {
printf("%d\n", i);
/* however there is no way to return this value:
* you can only return one time, that ends the function */
}
}
int main(int argc, char **argv) {
count_to(10);
return 0;
}
#include <stdio.h>
/* This is the easiest way to keep state: a global variable */
int i = 1; /* for(i = 1; ...) */
int count_to(int target) {
if(i <= target) { /* for(...; i <= target; ...) */
/* Now this function will print once per call. The function ends, but
* the state is persisted for the next call */
printf("%d\n", i);
/* (we could return a value instead of printing) */
i++; /* for(...; i++) */
return 1; /* We tell the user of this function whether to keep going */
} else {
return 0; /* ... or stop */
}
}
int main(int argc, char **argv) {
int counting = 1;
while(counting) {
counting = count_to(10);
}
return 0;
}
#include <stdio.h>
/* This is the same thing without global variables. It is idiomatic C code */
/* Use a struct because there are multiple variables. If there was only one, we
* could get away with just passing a pointer to that.
* This is what strtok_r() does for example (the "state" is the saveptr) */
struct count_state {
/* Note that those are the local variables of our first implementation :) */
int i;
int target;
};
void count_init(struct count_state *state, int target) {
state->i = 1; /* for(i = 1; ...) */
state->target = target;
}
int count_next(struct count_state *state) {
if(state->i <= state->target) { /* for(...; i <= target; ...) */
printf("%d\n", state->i);
state->i++; /* for(...; i++) */
return 1;
} else {
return 0;
}
}
int main(int argc, char **argv) {
int counting = 1;
struct count_state state;
count_init(&state, 10);
while(counting) {
counting = count_next(&state);
}
return 0;
}
.PHONY: all
all: 01-orig 02-global 03-struct
%: %.c
cc -Wall -Wextra -Wno-unused-parameter -ansi -pedantic -o $@ $<
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment