Amit Kumar
Amit Kumar

Reputation: 113

using bool in c (within a structure)

I wanted to use a boolean variable in c as a flag,within a structure,but c does not have any keyword "bool" to make it possible. I got some relevant information here : Using boolean values in C then basically,I tried this

struct bookshop
{
    char name[20];
    char issuer[20];
    int id;
    typedef enum { false, true } flag;

};

to get the following error,on this line:"typedef enum { false, true } flag"; Multiple markers at this line - expected specifier-qualifier-list before ‘typedef’ - Type 'flag' could not be resolved - Syntax error

please help! and thanks in advance :)

Upvotes: 3

Views: 18160

Answers (4)

Iharob Al Asimi
Iharob Al Asimi

Reputation: 53006

If you just want to declare the variable of type enum, inside the structure definition you should not use typedef.

The typedef is used to define a type, a user defined type and that's not what you want, you want to declare a variable which in turn is a member of the structure, so

struct bookshop
{
    char name[20];
    char issuer[20];
    int id;
    enum { false, true } flag;    
};

should do it.

Also note, that there is a standard header stdbool.h so that you can do this

struct bookshop
{
    char name[20];
    char issuer[20];
    int id;
    bool flag;    
};

Upvotes: 2

FloppySoftware
FloppySoftware

Reputation: 111

Traditionally, the int type was used to hold 'boolean' values: true for non zero values, and false for zero ones.

Since C99, you could use the macros and values defined in stdbool.h:

bool _Bool

true integer constant 1

false integer constant 0

__bool_true_false_are_defined integer constant 1

But be aware of compatibility with old code, and the way standard C tests values as true or false. As explained before, following code:

int flag = 4;

if(flag) {
     puts("true\n");
}
else {
     puts("false\n");
}

will print true.

Upvotes: 0

dbush
dbush

Reputation: 223739

You can't put a typedef inside of a struct definition like that. It needs to be at the global level.

typedef enum { false, true } bool;

struct bookshop
{
    char name[20];
    char issuer[20];
    int id;
    bool flag;
};

If you have stdbool.h available, you can just include that and it will provide the bool type as well as the true and false constants.

Upvotes: 6

Paul Ogilvie
Paul Ogilvie

Reputation: 25286

You cannot define a new type in a declaration. You first have to declare the bool typedef and then you can use it your struct, i.e.:

typedef enum { false, true } bool;

struct bookshop
{
    char name[20];
    char issuer[20];
    int id;
    bool flag;
};

Upvotes: 1

Related Questions