Is there any standard way to use boolean? because my code is giving an error
#include<stdio.h>
boolean ch(char x)
{
if(x>=48&&x<=57)
return 1;
else
return 0;
}
main()
{
if(!ch('t'))
printf("it's a character");
}
error:
cha.c:3: error: boolean' does not name a type
cha.c: In function
int 开发者_开发知识库main()':
cha.c:15: error: `ch' was not declared in this scope
Yes, the C99 standard has introduced the _Bool
type
Update
Apparently <stdbool.h>
also includes the prettier bool
type in addition to the true
and false
macros. Updated code to reflect this.
#include <stdio.h>
#include <stdbool.h>
bool ch(int);
int main(void)
{
if(!ch('t'))
printf("it's a character\n");
return 0;
}
bool ch(int x)
{
if (x >= 48 && x <= 57)
return true;
else
return false;
}
Click this link to see the compiled code's output
And googling wins again
Boolean Expressions and Variables : What is the right type to use for Boolean values in C? Is there a standard type? Should I use #defines or enums for the true and false values?
Unless I'm crazy, C doesn't have a boolean
type. Change the return type of ch
to int
Also, post your error message.
C does not have a built-in boolean
type. A bool
type is available in the stdbool.h
header in the standard library in C99.
http://en.wikipedia.org/wiki/Stdbool.h
You've got more problems than just the type, however. if(x>=48&&x<=57)
doesn't mean what you think it does, and your printf is going to give you unexpected results too.
You're going to need these characters: "(())\n" and a bunch of whitespace.
Sorry to be a little cryptic but this looks like a homework problem.
The conditional statement if (boolean_expression) return true; else return false;
can always be replaced by return boolean_expression;
which I find a lot more readable.
Also, your naming is terrible, what does ch
stand for? Since 48 is 0
and 47 is 9
, a better name would probably be is_digit
or something. (And, as others have noted, C89 does not have a boolean type.)
int is_digit(char c)
{
return (c >= '0') && (c <= '9');
}
The parenthesis are optional, but I think they make the code more readable.
And what do you mean by the output "It's a character" in main? Every char
is a character, duh :)
精彩评论