• 01-12-2009
Crocodile23
I'm trying to study how the functions in C work.

First: Does anyone has any good book that deals specifically with functions in C?

I'm very puzzled about the recursiveness of functions and how it really works. How exactly a function calls itself (with other values) when it's inside itself and how the values change.

For example in the following code............:

Code:

```#include "stdio.h" #define max(a,b) (a)>(b)? a : b int g=0; int ab(int n, int a) {     if (n==0) return 5;     printf("a=.....%d\n",a);     printf("g=.....%d\n",g);     printf("-------------\n");         g=-50;     a-=1;         g=max(g,ab(n-1,a));         printf("a(%d)==========%d\n",n,a);         return g; } void main(void) {         ab(2,10); }```
........... i had the impression that it should return the output:

a=.....10
g=.....0
-----------------
a=.....9
g=.....-50
-----------------
a(1)========8
a(2)========9

But instead it returns the output:

a=.....10
g=.....0
-----------------
a=.....9
g=.....-50
-----------------
a(1)========8

a=.....9
g=.....5
-----------------
a(1)========8
a(2)========9

Why it does that?
Can anyone explain step by step why it prints the extra(red) lines?
• 01-12-2009
matsp
Because you are calling ab() inside itself, and ab() produces that sort of output?

--
Mats
• 01-12-2009
MK27
Code:

```#include "stdio.h" #define max(a,b) (a)>(b)? a : b int g=0; int testfunc (int X, int Y) {         return max(X,Y); } int ab(int n, int a) {     if (n==0) return 5;     printf("a=.....%d\n",a);     printf("g=.....%d\n",g);     printf("-------------\n");         g=-50;     a-=1;         g=testfunc(g,ab(n-1,a));         printf("a(%d)==========%d\n",n,a);         return g; } void main(void) {         ab(2,10); }```
Produces the expected:
a=.....10
g=.....0
-------------
a=.....9
g=.....-50
-------------
a(1)==========8
a(2)==========9

ps. look for stuff about the Fibonacci set, that is the essential form of recursion I think
• 01-13-2009
Elysia
Main returns int; not void.
• 01-13-2009
BEN10
Quote:

Does anyone has any good book that deals specifically with functions in C?
try Tanenbaum-data structures using c & c++.it deals with recursive functions in great detail.