Here is the program that I am trying to compile
#include<stdio.h>
int main()
{
int i = 0;
rec(i);
}
int rec(int i)
{
i = i + 1;
if (i == 10){return true;}
rec(i);
printf("i: %d\n", i);
}
I am getting this output
$ gcc -o one one.c
one.c: In function ‘rec’:
one.c:10:24: error: ‘true’ undeclared (first use in this function)
one.c:10:24: note: each undeclared identifier is reported only once for each function it appears in
As far I believe is Boolean true evaluates to 1 in c. If so why am I getting an error?
There are no
trueorfalsekeywords in C. There are some library definitions for those values instdbool.h(starting in C99, I think) but oft times most C programmers will just use1and0.If you don’t want to use
stdbool.h, or you’re working on a compiler that doesn’t support it, you can usually define the constants yourself with something like:or you can use
1and0directly – the method above is for those who don’t want to have to remember which integer values apply to which truth values (a).0is false, any other value is true. So your code would look something like (fixing up the return value problem as well though I’m not sure why that’s even there since it always returns true.):which gives you:
I should also mention that recursion is a solution best used when the search space is reduced quickly, such as in a binary tree search where the search spaces halves on each recursive call. It’s not usually a good fit for something where you just increment a value on each call although, in this case, it’s probably okay since you limit it to about ten levels.
(a): Keep in mind the caveat that, although the given definition of TRUE will most be 1, any non-zero value will be treated so. That means that the two statements:
do not mean the same thing. There are a large number of possible
isValidvalues which will be pass the first test but fail the second. That’s usually not a problem since it’s almost always a bad idea to compare boolean variables with boolean constants anyway.