Skip to content

Instantly share code, notes, and snippets.

@ZumiKua
Last active August 29, 2015 14:25
Show Gist options
  • Save ZumiKua/ac47b1601ffd6d40b92d to your computer and use it in GitHub Desktop.
Save ZumiKua/ac47b1601ffd6d40b92d to your computer and use it in GitHub Desktop.
Compute 1+2+3+4+5 in C without using if and while
//Inspired by http://www.zhihu.com/question/20125963/answer/18158192 (chinese)
#include<stdio.h>
#include<stdlib.h>
#define MAXN 5
typedef void* (*loop_func)(void* params);
typedef void (*branch)(loop_func,void*);
void conditionFalse(loop_func loopfunc,void* params){
(*loopfunc)(params);
}
void conditionTrue(loop_func loopfunc,void* params){
int* pi = (int*)params;
char* pch = (char*)(pi+1);
int* psum = (int*)(pch+1);
printf("i=%d,ch=%c,sum=%d\n",*pi,*pch,*psum);
free(params);
}
void* loop(void* params){
int* pi = (int*)params;
char* pch = (char*)(pi+1);
int* psum = (int*)(pch+1);
(*pi)++;
(*psum)+=(*pi);
(*pch)++;
branch* branches;
branches = (branch*)malloc(sizeof(branch)*2);
branches[0] = &conditionFalse;
branches[1] = &conditionTrue;
(*branches[((*pi)==MAXN)%2])(&loop,params);
free(branches);
}
int main(int argc,char** argv){
void* params = malloc(sizeof(int)*2+sizeof(char));
int* pi = (int*)params;
char* pch = (char*)(pi+1);
int* psum = (int*)(pch+1);
(*pi) = 0;
(*pch) = 'A';
(*psum) = 0;
loop(params);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment