how to work with boolean function in c - c

Anyone please tell me, what is wrong in this code
#include<stdio.h>
bool func(char *,int);
void main()
{
char *a="Interview";
if(func(a,9))
{
printf("True");
}
else
{
printf("False");
}
}
bool func(char *s, int len)
{
if(len < 2)
return true;
else
return s[0] == s[len-1] && func(&s[1], len-2);
}
I believe this function always returns TRUE. This is an interview question. But, when I try to compile this, it shows 6 errors..

I'm going to guess it doesn't know what bool and true are. bool is not a primitive data type in C you need an extra include:
#include <stdbool.h>
The second part of your question? Does it always return TRUE?
No:
When you come into the function you'll skip the first return because your length is 9. So instead you'll return if true only if:
return s[0] == s[len-1] && func(&s[1], len-2)
Is true. You can skip the recursive logic here because it's not modifying your string, just look at the first part:
s[0] // this has to be 'I'
== // we need so what we compare against has to be 'I' as well
s[len-1] // This will be 'w'
So... that's not going to return true... who cares about ANDing (&&) the recursive part? I suspect the compiler will even optimize that out because everything here is hardcoded.

You just have to include the right header.
#include <stdbool.h>
Or, you can use _Bool type, which don't need any inclusion. bool is just an alias from this type. By the way, don't forget to compile in C99.

Related

Ambiguity about Boolean functions in C

Part of my C code 1:
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
[snip!!]
#define FALSE 0
#define TRUE 1
[snip!!]
typedef int Boolean;
[snip!!]
typedef struct {
int identification ;
char name[NAMESIZE] ;
char subject[SUBJECTSIZE] ;
int grade ;
} RECORD ;
typedef struct {
char type ;
RECORD student ;
} TRANSACTION ;
typedef struct {
char occupied ;
RECORD student ;
} MASTER ;
char *prog ;
Boolean get_transaction_record(FILE *fp, TRANSACTION *transaction);
[snip!!]
void main(int argc, char *argv[])
{
FILE *fpmas,*fptrans ;
int current_key ,
relative_record_number ;
Boolean allocated;
TRANSACTION transaction;
MASTER master ;
clrscr();
prog = argv[0];
[snip!!]
else
{
get_transaction_record(fptrans, &transaction) ;
current_key = choose_next_key(transaction.student.identification);
while(current_key != TRAILER)
{
relative_record_number = do_initial_status(
current_key,&allocated, fpmas,&master);
while(current_key == transaction.student.identification)
{
apply_transaction (&allocated, &transaction,&master) ;
get_transaction_record(fptrans, &transaction);
}
do_final_status (fpmas, relative_record_number, allocated, &master);
current_key = choose_next_key(transaction.student.identification);
} //end of while
fcloseall();
} //end of else
}
Part of code 2:
Boolean get_transaction_record(FILE *fp, TRANSACTION *transaction)
{
if (fscanf (fp, "%4d%c%20s%10s%2d",
&transaction -> student. Identification,
&transaction -> type,
transaction -> student.name,
transaction -> student. Subject,
&transaction -> student. Grade) == 5)
return(TRUE);
return(FALSE);
}
How these return(); work (in the screenshot I attached) ?! I see before Boolean application like this typedef int Boolean; before. But that usage was in accompany with if() . But I do not see any if() in this code!
My main question is, how it works when the return value (TRUE or FALSE), get back to main() function'?! In main(), there is no condition evaluation to take decision about that (TRUE or FALSE) returned value. So what?
Boolean - return
First, your C learning book is largely outdated. C99 (out in 1999) allows #include <stdbool.h> that contain a bool type and true/false defines, use these instead of making your own boolean.
C and many other languages are a bit weird with boolean, if and what is true of false. In C what is 0 is false, everything else is true, hence why TRUE is defined as 1 and FALSE defined as 0 in your book. Note that comparison operators such as ==, &&, ||, ! (not to be confused with binary operators &, |, ~) returns either 1 or 0 depending of the condition.
See this example:
#include <stdio.h>
#include <stdbool.h>
bool return_the_truth(void)
{
return true; // A trivial function that returns true.
}
int main(void) {
if (2)
printf("As you see just \"2\" is true since it's different of zero\n");
if (0)
printf("That line won't be printed\n");
if (4 - 4)
printf("Neither this one since 4-4 is zero\n");
if (true == 1)
printf("true is in fact a one.\n");
if (true == 2)
printf("But merely a integer with value 1 so this line won't print.\n");
// You can invoke a function that returns a boolean and ignore it's return value.
return_the_truth();
// It is never mandatory to use the returned value. This example is absurd but perfectly valid
fopen("delete_me.txt","a"); // <- Don't forget to delete this file afterward.
if (printf("printf() return an int that is the numbers of characters printed.\n"))
printf("Hence again, this line is printed because what in the if() is not zero.");
int boolean_check_result = 42 == 40+2;
if (boolean_check_result)
printf("You can write expressions like this, there boolean_check_result is %d.\n",boolean_check_result);
printf("You can performs math with boolean, there is %d true expressions there, it works because a comparison returns 1 if true, 0 if false and we doing a sum of 1 and zeros (it's brainfuck to understand don't do that or people reviewing your code will hate you).\n",
(4 == 5) + (4 < 5) + (4 != 5) + (4 > 5) + (4 >= 5) // <- The expressions.
);
// These examples below are valid C.
5 + 6; // This sum goes to... nothing
7 == 7; // Same for this boolean, nothing will happen
printf; // Functions are kind of constants variables so that works.
// It's a non-sense, a compiler will output warnings because making computations without using the results is likely a programming error.
printf("But remind you that in the case of a function (returning a boolean or not), there might be side-effects you want and don't care about the returned value such as with this printf().\n");
}
// Did you know that you can use a `void` value ?
// The code below is perfectly valid.
// It's useful for C++ wrappers when you want to exactly mimic the behavior a library in order to catch errors.
void a_function_that_does_nothing(void)
{
}
void you_can_return_a_void(void)
{
return a_function_that_does_nothing(); // Allowed because the function return a void
}
There is tons of valid case where a returned boolean are not used inside a if().
So to answer your original question (that I might forgot while writing this answer hehe...):
how it works when the return value (TRUE or FALSE), get back to main()
function'?!
And ! 🥁 🥁 🥁 Nothing happens. The value is just lost, just like with printf() and any other functions. In the book the boolean value was an error indicator since scanf() return the number of inputs read, not 5 mean that the input was incorrect.
Not checking it is fine for learning purposes. In real-world input parsing, first don't use scanf(), then it could introduce a security vulnerability since some variables would not be written and in incorrect state and trigger unwanted behavior later that can be exploited by a malicious hacker to leak sensitive data of thousands of customers and costs millions of USD to a company (I'm barely exaggerating).
So don't be outraged when a boolean or other returned value is not used, memcpy() is a function where it's commonly sane to ignore it's return value. What is important is to understand what you are doing.
If you're still extremely angry about the fact that this boolean wasn't used and could avoid a potential security vulnerability... (I'm joking there, yet) as an exercise you can add error checking and do something useful such as printing an expressive error message telling the user that the input is incorrect and remind they what you are expecting and quit.

What is the proper equivalent of "while(true)" in plain C?

Since C doesn't have bools, what is the proper variable to put in place of true in an algorithm that uses
do
{
// ...
} while(true);
???
Should a proper C programmer do
do
{
// ...
} while(1);
or is there a specific variable reserved to mean "something that is not zero/NULL" ?
Usually nowadays I see
while(1) {
...
}
It used to be common to see
for(;;) {
...
}
It all gets the point across.
Your question isn't really about bool (which modern C does have if you #include <stdbool.h>), it's about the best way to write an infinite loop.
Common idioms are:
while (1) {
/* ... */
}
and
for (;;) {
/* ... */
}
The latter looks a little obscure, but it's well-defined. Any of the three expressions in a for loop header can be omitted; if the second expression, which controls when the loop continues to execute, is omitted, it defaults to true.
while (1) is probably the most straightforward method -- but some some compilers might warn about a condition that's always true. for (;;) likely avoids that, since there is no (explicit) expression to warn about.
I personally wouldn't use a do/while loop, because the condition is at the bottom.
There are trickier ways to write an infinite loop (while (1 + 1 == 2) et al, but none of them are really worth the effort.
Either while (1) or for (;;) will be perfectly clear to anyone with a good understanding of C.
If you're using c89:
Create a boolean definition:
typedef int bool;
#define true 1
#define false 0
Or constants:
/* Boolean constants. */
#define TRUE 1
#define FALSE 0
This gives the int a meaning for you.
Or (as mentioned elsewhere here) if using c99:
#include <stdbool.h>
My experience of universities lately, is they require you to use c89.
http://en.wikipedia.org/wiki/C_data_types#stdbool.h
C has stbool.h header file to use bool variables.
So this works
#include <stdio.h>
#include<stdbool.h>
int main(void) {
int i=1;
while(true)
{
if(i==3){
break;
}
printf("%d\n",i);
i++;
}
return 0;
}
Output
1
2
note:Modern C99 has support for bool variables but C89/90 does not have.
If you are using C89/90 then you can use typedef or constants as mentioned in one of the answers here or you can use enums as well like this
typedef enum {false, true } bool;
bool b=true;
int i=1;
while(b)
{
if(i==3){
break;
}
printf("%d\n",i);
i++;
}
output
1
2
You can check this bool in C
Hope it helps you.

"Logical or" and "logical and" if statement in c different output despite looking the same

So I got this code sample I wrote. My goal was to print the numbers in the sentence that is stored in the ptr char variable. So the first part of the code does the job.
#include <stdio.h>
#include <stdlib.h>
void preg(char *p);
int main(int argc, char *argv[])
{
char *ptr;
ptr="John is 5 , jim is 2 and maria is 12";
preg(ptr);
return 0;
}
void preg(char *p)
{
while(*p!='\0')
{
if(*p>='0' && *p<='9')
{
putch(*p);
}
*p++;
}
}
But if I change the preg function into :
void preg(char *p)
{
while(*p!='\0')
{
if(*p>='0' || *p<='9')// <--- Changed to logical or
{
putch(*p);
}
*p++;
}
}
The program prints the whole sentence ? It's seems strange to me cause in this case both logical operators seems suitable for the given task. I hope someone will explain me the difference. I suspect it has to do something with the way characters are represented as integers when they are compared with numbers.
*p>='0' || *p<='9' is equivalent to true, since '9' >= '0'.
You should take care of the short-circuit evaluation, it will help you to understand that behavior.
Actually, all the expressions of *p>='0' || *p<='9' will not necessarily be evaluated. In the case of the logical OR, if the first expression *p>=0 is true, the second one (*p<=9) will not be evaluated, because there's no need: the first one is true, then the condition is filled. It's an optimization to avoid unnecessarily expression evaluation.
So in your case, if *p is greater than 0, *p<='9' will never be evaluated, that's why you need to use the logical AND.

Passing an array through "isalpha" through a loop

I've been at this for quite some time now and the existing answers offer little to no help. I am new to programming and am trying to write a sub-part of my program which tries to check whether any given input is constituted solely of alphabets.
For this, the idea I have in mind is to pass an entire array through the isalpha function by using a loop which passes each character at a time. The idea makes logical sense but I am having syntactic trouble implementing it. I will greatly appreciate any help!
Below is my code-
printf("Please type the message which needs to be encrypted: ");
string p = GetString();
for (int i = 0, n = strlen(p); i < n; i++)
{
if(isalpha(**<what I'm putting here is creating the problem, I think>**) = true)
{
printf("%c", p[i]);
}
}
You should modify your code as this (assuming you have the string type defined yourself):
printf("Please type the message which needs to be encrypted: ");
string p = GetString();
for (int i = 0, n = strlen(p); i < n; i++)
{
if(isalpha(p[i]) == true) // HERE IS THE ERROR, YOU HAD =, NOT ==
{
printf("%c", p[i]);
}
}
Operator = is for assignment and operator == is for comparison!
So what was happening? The assignment resulted in true, no matter what p[i] was.
As Quentin mentioned:
if(isalpha(p[i]) == true)
could be more elegant and error prune if written like this:
if(isalpha(p[i]))
Here is an example in C:
/* isalpha example */
#include <stdio.h>
#include <ctype.h>
int main(void)
{
int i = 0;
char str[] = "C++";
while (str[i]) // strings in C are ended with a null terminator. When we meet
// the null terminator, while's condition will get false.
{
if (isalpha(str[i])) // check every character of str
printf ("character %c is alphabetic\n",str[i]);
else
printf ("character %c is not alphabetic\n",str[i]);
i++;
}
return 0;
}
Source
Ref of isalpha().
C does not have a string type.
Tip: Next time post your code as it is!
Aslo, as Alter noticed, it would be nice to use:
isalpha((unsigned char)str[i])
and in your code
isalpha((unsigned char)p[i])
for safety reasons.
Your example is here.
I.e. parameter of isalpha() is i-th character of string p. The only question is how to access to i-th character. Usually you can use []. I.e. just use following code: isalpha(p[i]) (I see that you already use [] in call of printf).
Also isalpha(p[i]) = true is wrong condition. It looks like you planned to check isalpha(p[i]) == true (you can skip == true).
Late but:
both other answers say omitting == true is desirable, but don't say it is necessary for portability.
The C core-language operators == != < <= > >= && || which return a 'logical' value use an int value of 1 for true and 0 for false. In C99 and up with stdbool.h and by common convention before that true is 1 and false is 0, so e.g. if( (a < b) == true ) will work correctly, although it is redundant and many (including me) consider it poor style. Language elements that test a logical value, namely if(c) while(c) for(;c;) and the operands to && || and the left operand to ?: consider any value that compares equal to 0 to be false, and any other value to be true.
The character-classification routines in ctype.h as well as some other standard-library routines like feof(f) and ferror(f) are specified to return some nonzero int for true and 0 (an int) for false, and on many implementations the nonzero value used for true is not (always) 1. In those cases isalpha(whatever) == true might result in testing say 4 == 1 and fail even when whatever is an alphabetic character. OTOH isalpha(...) != false or isalpha(...) != 0 does work correctly if you really want to write something explicit.

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 functionint 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 :)

Resources