r/C_Programming • u/MysticPlasma • Jun 05 '26
Question regarding recursion: Fibonacci as first C project!
Hello everyone! First off, I'm new to C, and I'm coming mainly from an assembly standpoint.
I started to write some C in a 'learning-by-doing' fashion, and as the title says, I got the recursive fibonacci algorithm to work!
However, I had to fight with the language itself, and I'm quite disappointed with the lack of granular control the language provides.
Here is the code, I'm open for criticism (but could also do without :P):
// shortening
typedef unsigned char u8;
typedef unsigned short u16;
// initializing the system
static u8 ram[0x10000] __attribute__((aligned(2))) = {0};
// why can't I use the register type modifier here,
// the memory location here are not specified, this looks like UB!
// Addendum: After some testing, these locations seem to live on some random location,
// all I can do is trust that they exist
/*register*/ static u16 r0, r1, fp, sp;
// since the C standard doesn't even provide the status flags themselves:
static struct {
u8 Z, L;
} sr = {0x0000};
// The value we pass to the function as argument
static u16 N;
// need to keep in mind that call pushes the current pc
// this is a stub in practice
#define call sp += 0xfffe;
// also, add the return counterpart with the sp stub in-place
#define ret sp += 0x0002; return;
// to ease the asm habits
#define jnz goto
#define label
void fibonacci(void);
void prologue(void) {
// some prologue stuff
sp += 0xfffe;
*(u16*)(&ram[(u16)(sp)]) = fp;
fp = sp;
sp += 0xfff8;
*(u16*)(&ram[(u16)(0x0169)]) = N;
*(u16*)(&ram[(u16)(0xfffa + fp)]) = 0xffff;
// prepare the reference to be passed
*(u16*)(&ram[(u16)(0xfff8 + fp)]) = 0xfffa + fp;
// first pushing the return value pointer as argument 1
sp += 0xfffe;
*(u16*)(&ram[(u16)(sp)]) = *(u16*)(&ram[(u16)(0xfff8 + fp)]);
// then pushing the value N as argument 0
sp += 0xfffe;
*(u16*)(&ram[(u16)(sp)]) = *(u16*)(&ram[(u16)(0x0169)]);
// and finally call the actual function
call fibonacci();
// free arguments from stack
sp += 0x0004;
// set r0 to the final result
r0 = *(u16*)(&ram[(u16)(0xfffa + fp)]);
// some epilogue stuff
sp = fp;
fp = *(u16*)(&ram[(u16)(sp)]);
sp += 0x0002;
ret;
}
void fibonacci(void) {
// some prologue stuff
sp += 0xfffe;
*(u16*)(&ram[(u16)(sp)]) = fp;
fp = sp;
sp += 0xffe8;
// first I need to retrieve the result pointer argument
// since fp starts at the current scope and the last scope just pushed the arguments -
// we can reach them by skimming over the pushed pc at 0x0002 + fp and grab them from there.
*(u16*)(&ram[(u16)(0xfffe + fp)]) = 0x0006 + fp;
r1 = *(u16*)(&ram[(u16)(0xfffe + fp)]);
*(u16*)(&ram[(u16)(0xfffc + fp)]) = *(u16*)(&ram[(u16)(r1)]);
// secondly I need to retrieve the actual N value
*(u16*)(&ram[(u16)(0xfffa + fp)]) = 0x0004 + fp;
r1 = *(u16*)(&ram[(u16)(0xfffa + fp)]);
*(u16*)(&ram[(u16)(0xfff8 + fp)]) = *(u16*)(&ram[(u16)(r1)]);
r0 = *(u16*)(&ram[(u16)(0xfff8 + fp)]);
// do the termination on values less than or equal 0x0001
// ugly workaround because of course C doesn't allow me to use the Status Registers themselves...
{
sr.Z = r0 == 0x0001;
sr.L = r0 < 0x0001;
}
r1 ^= r1;
if (!sr.L) {
r1 = 0x0001;
}
if (sr.Z) {
r1 = 0x0000;
}
*(u16*)(&ram[(u16)(0xfff6 + fp)]) = r1;
// evaluate the condition and skip early return if true
{
sr.Z = r1 == 0x0000;
}
if (!sr.Z) {
jnz skip_early_return;
}
// do early return here
r1 = *(u16*)(&ram[(u16)(0xfff8 + fp)]);
r0 = *(u16*)(&ram[(u16)(0xfffc + fp)]);
*(u16*)(&ram[(u16)(r0)]) = r1;
// some epilogue stuff
sp = fp;
fp = *(u16*)(&ram[(u16)(sp)]);
sp += 0x0002;
ret;
label skip_early_return:
// first call fibonacci again, but with N + 0xfffe as the argument
*(u16*)(&ram[(u16)(0xfff2 + fp)]) = 0xfff4 + fp;
// first push the pointer to stack allocated result
sp += 0xfffe;
*(u16*)(&ram[(u16)(sp)]) = *(u16*)(&ram[(u16)(0xfff2 + fp)]);
// then the new argument
sp += 0xfffe;
r1 = *(u16*)(&ram[(u16)(0xfff8 + fp)]) + 0xfffe;
*(u16*)(&ram[(u16)(sp)]) = r1;
call fibonacci();
sp += 0x0004;
// then call fibonacci again, but with N + 0xffff as the argument
*(u16*)(&ram[(u16)(0xffec + fp)]) = 0xffee + fp;
// same as above
sp += 0xfffe;
*(u16*)(&ram[(u16)(sp)]) = *(u16*)(&ram[(u16)(0xffec + fp)]);
// same as above
sp += 0xfffe;
r1 = *(u16*)(&ram[(u16)(0xfff8 + fp)]) + 0xffff;
*(u16*)(&ram[(u16)(sp)]) = r1;
call fibonacci();
sp += 0x0004;
// now accumulate the results fib(N+0xfffe) + fib(N+0xffff)
r1 = *(u16*)(&ram[(u16)(0xfff4 + fp)]);
r1 += *(u16*)(&ram[(u16)(0xffee + fp)]);
*(u16*)(&ram[(u16)(0xffe8 + fp)]) = r1;
// and store it in the return pointer to traverse upstream
r0 = *(u16*)(&ram[(u16)(0xfffc + fp)]);
*(u16*)(&ram[(u16)(r0)]) = *(u16*)(&ram[(u16)(0xffe8 + fp)]);
sp = fp;
fp = *(u16*)(&ram[(u16)(sp)]);
sp += 0x0002;
ret;
}
int main(void) {
r0 = 0x0000;
r1 = 0x0000;
fp = 0x0000;
sp = 0x7f00;
N = 0x0010;
call prologue();
// and now doing literal magic
// Thanks to https://stackoverflow.com/questions/68252697/syntax-of-printf-in-c
#include <stdio.h>
printf("fib(%d): %d\nsp: %.4x\n", N, r0, sp);
// and since sp is 0x7f00, we didn't even get a stack memory leak!
return 0;
}It does work, but it took hours and hours of head-banging to get there. This is obviously not production ready, for example, I know I'm allocating too much stack memory in the prologue, that's a symptom of previous stack-allocated debugging variables that were removed.
I tried to make the comments verbose, though I feel like maybe I should have made each line of code more granular, because I'm summerizing quite a few lines per comment.
Im also proud that I was able to take advantage of some the, in my opinion, obscure features of the C language:
As you can see in my code, I was able to add a workaround of a lacking C-feature by making use of the '<' and '==' sigils!
Ok, now finally to my actual question and main concern:
Since my peers are quite pedantic and told me that using inline assembly is basically cheating, I'm wondering, how else am I supposed to manage the argument passing without sacrificing the atomicity of the fibonacci function? Should the caller or callee take the responsibility?
Any and all responses are welcome!
sincerely \s & \j
2
u/duane11583 Jun 06 '26
If you are using GCC I suggest you learn about the -s option
It’s how I learned c along 35-40 years ago
Write something very small compile that and see what the compiler produces
To this day when I am after something still think in asm mode
2
u/Amelia_SadAllDay Jun 07 '26
Damn, reminds me of one time I implemented stack frames in my own stack based language that compiles into 6502 assembly and first thing I did was Fibonacci Soo, I guess, pretty much solid work.
58
u/llynglas Jun 05 '26
Has to be trolling. Right?
13
u/CarlRJ Jun 06 '26
😂 I'm totally stealing this.
36
u/non-existing-person Jun 05 '26
See? That's exactly the code I would expect from someone with academia experience and not a real world one. It's advanced. It's cool. It's really smart. It's almost magical.
It's absolute utter unreadable garbage.
Why are you using this
ramvariable? Why not just use normal variables? Manual stack pointer manipulation? I mean, if you wanted to simulate CPU it's fine. But if you just wanted to do program that works, it's just... stupid.Don't write C as if you wrote pure assembly. C takes care of your stack and stack pointer for you. Use that. This is not C code. It's 3 assembly guys in a trench code.
Recursive fibonacci is just
C takes care of function call stack, and stack pointer. That's it. Just call it in main and you're done. No need for that huge amount of code you did. That's not how you write C.
9
u/mc_pm Jun 05 '26
That is the craziest thing I've seen in a long time.
17
u/DankPhotoShopMemes Jun 06 '26
legendary shitpost
7
u/[deleted] Jun 06 '26
Lmao you got me 😂😂😂😂😂😂😂
4
u/flyingron Jun 05 '26
In addition to all the other stuff, char is not necessarily unsigned. It's implementation defined as to whether it is signed or not. Just another stupidity of C, where we ask char to do tripple duty as:
6
u/dydhaw Jun 05 '26
Hey not bad for a first attempt! Instead of using the obscure function call syntax you could simplify the printf call by pushing the arguments to the stack and calling the symbol address directly.
8
u/Trick-Apple1289 Jun 06 '26
Best post on here in a while, looking at the comments I see sense of humor is not a trait that C programmers possess ;)
good post op
4
u/SmokeMuch7356 Jun 05 '26 edited Jun 06 '26
Is this a joke? I feel like this is a joke. But in case it isn't:
registerandstaticare mutually exclusive; they're different storage classes with opposite meanings.registeris largely vestigial at this point anyway; the only practical effect is that you can't use the unary&operator on aregisterobject:As for the rest of your code:
...look, if you're going to write C code, write C code. Using the preprocessor to make C look more like assembly doesn't make it behave like assembly and it will bite you in the ass. I'm not going to comment on the structure of the code because it's not C.
I went through this crap in college when all my professors gave us code written in Cscal or CTRAN. It's bad practice. Don't do it.
If you need assembly, write assembly. Don't write some half-assed implementation of pseudo-assembly in C. It is not worth the heartburn.
A naive recursive Fibonacci implementation in C basically looks like:
...remembering that Fibonacci, along with factorials, is an awful, horrible, stupid example of recursion, in any language. For any sufficiently large value of
nyou will be computing the same terms thousands of times. Like:You're computing
f(3)twice, meaning you're computingf(2)3 times. And that doesn't grow linearly. No, no, no, no. Thousands of calls before you start getting anywhere near the limits of whatintcan represent.4
u/ThatIsATastyBurger12 Jun 06 '26
This was spectacular
2
u/dnabre Jun 06 '26
If you want a recursive Fibonacci in C, that avoids recalculating intermediate terms, you shouldn't be writing assembly in C. You should be writing Scheme in C:
Check it out on Compiler Explorer (aka godbolt)
1
u/Helpful-Primary2427 Jun 05 '26
This has to be a troll
1
u/Daveinatx Jun 06 '26
Redefine to
jz0
u/Signal_Cranberry_479 Jun 05 '26
Yes
1
u/[deleted] Jun 06 '26
[removed] — view removed comment