user1133324
user1133324

Reputation: 143

Cannot return bool from function

This is the piece of code in base C:

static bool is_ascii_value_of_digit(char ascii_value){

    if((ascii_value<40)&&(ascii_value >= 30)){
        return true;
    }
    return false;
}

The avr studio gcc compiler is giving me error :

../calculator.h:4: error: expected '=', ',', ';', 'asm' or '__attribute__' before 'is_ascii_value_of_digit'

Similar errors are also evident in other functions. I do not know why this is happening. Spent an hour figuring out why and finally gave up. As far as I have seen online, my syntax is not the problem. Probably something that I am overlooking.

Question RESOLVED !

Thank you very much for your quick help as it saved me a lot of time. I was under the assumption that bool is a keyword in c.

Upvotes: 2

Views: 11442

Answers (4)

GiantRobot
GiantRobot

Reputation: 432

According to http://computer.howstuffworks.com/c11.htm i used it many years ago

#define True  1
#define False 0
typedef int boolean;

void main(void)
{
    boolean b;

    b=False;
    if(!b) printf("false");

}

In codepad output is false

http://codepad.org/iWKiFHFA

Upvotes: 0

Keith Thompson
Keith Thompson

Reputation: 263227

If your compiler supports, at least partially, the C99 standard (or C11, but that's not yet likely), add

#include <stdbool.h>

to the top of your source file to make bool, false, and true visible.

If it doesn't (Microsoft's support for C99 is not good), a workaround is:

typedef enum { false, true } bool;

This doesn't quite match the semantics of C99's bool (actually _Bool) type, but it's probably close enough.

Incidentally, you don't need an if/else statement in your function:

static bool is_ascii_value_of_digit(char ascii_value) {
    return ascii_value >= '0' && ascii_value <= '9';
}

bool values are values, and they can be stored and returned from functions just like any other values.

Another guideline: Don't compare boolean values to true or false, just test them directly. In a condition (such as in an if statement), any non-zero value is considered true, so this:

if (cond == true) ...

can fail if cond has non-zero value other than 1. Just write:

if (cond) ...

or, to test whether it's false:

if (!cond) ...

Recommended reading: section 9 of the comp.lang.c FAQ. (Further recommended reading: all the rest of the sections.)

Upvotes: 3

Daniel Fischer
Daniel Fischer

Reputation: 183858

You probably have just forgotten to #include <stdbool.h>.

However, you have a mismatch between name and behaviour of your function,

if((ascii_value<40)&&(ascii_value >= 30))

the decimal digits, 0-9, occupy the places 48-57 in the ASCII table, that's hexadecimal 0x30-0x39, so to match the name, you should test

if (ascii_value < 0x3A && ascii_value >= 0x30)

Upvotes: 4

Xion
Xion

Reputation: 22770

C does not have bool type, neither true or false. Use int and 0/1 values instead.

Upvotes: 3

Related Questions