What does the ! operator do in this situation? [duplicate] - c

This question already has answers here:
Using Exclamation Marks '!' in C
(5 answers)
Closed 2 years ago.
I am learning C from a textbook, and I stumbled onto the code of a function, where the following part had little explanation to what it does. It looked something like this:
int func(char *a, char *b) {
if(!a || !b)
return 0;
return 1;
}
My understanding is it checks that a and b are not null? Is this correct? Any help is welcome for this beginner :)

! is the logical not operator.
The if condition !a || !b is true if either a or b are zero, i.e. NULL pointers. Then the func returns 0 in that case, 1 otherwise:
a b condition func
null null true 0
null non-null true 0
non-null null true 0
non-null non-null false 1
It is easier to understand if you negate the condition and swap the return values:
int func(char *a, char *b) {
if(a && b)
return 1;
return 0;
}
Since in C the relational operators give their result as an int, i.e. 0 for false and 1 for true, you can simplify further to:
int func(char *a, char *b) {
return a && b;
}

Not exactly. When a is null or b is null then the logical NOT operator will cause the if conditional to evaluate as true and the return value is zero, otherwise the code returns 1 indicating that either a or b is not null.

The ! operator in most programming languages reverses the logic(or the not operator). i.e.(From True to False or vice versa)
For example:
a=True;
if(!a) {
return 1;
}else {
return 2;
}
Output is 2. So in this case, you are saying if not A OR not B, return 0.

Related

Function passed to if statement

I have a little confusion about this statement.
if( Ql_StrPrefixMatch(strURC, urcHead) )
{
callback_NTPCMD((char*)strURC);
}
The source code of Ql_StrPrefixMatch is:
s32 Ql_StrPrefixMatch(const char* str, const char *prefix)
{
for ( ; *str != '\0' && *prefix != '\0' ; str++, prefix++)
{
if (*str != *prefix) {
return 0;
}
}
return *prefix == '\0';
}
How is the if-statement evaluated to True or False based on the returns of Ql_StrPrefixMatch function, because it either returns 0 or *prefix == '\0'?
Does return of 0 mean False?
Please help me to explain this point.
Thank you in advance
....because it either returns 0 or '\0'?
No, the second return statement uses a comparison operator, not an assignment. That returns either 0 or 1. That return value is used to evaluate the if statement.
s32 is a signed integer. The function returns eigther 0 or 1. C then interprets this as a bool.
Why does the function return 1?
*prefix == '\0' gives a bool, which then is converted to s32.
Yes, indeed, you are current. 0 in c means false, and also, on the other hand, NULL or '\0' also evaluates to false. You can refer to this answer for your query. So as you can guess, if(0) and if('\0') will be evaluated to the false branch of the if statement. And also, additional information: Anything non-zero value will be evaluated as true.

Confusion with operator '!' in c

I've seen the operator ! being used in multiple places differently and I still don't get how it actually works. My basic understanding is it reverses the value from true to false and vice versa. If it reversed to true the statement triggers. Let's take an example.
int main(void)
{
int a = 5;
if (!(a == 6))
{
printf("unlike\n");
}
if (!(a == 5))
{
printf("like\n");
}
}
In the code above since a is 5 it ends up printing "unlike" because the false statement that a is 6 got reversed. Now let's take another example.
int main(void)
{
string i = "abc";
string j = "cab";
string k = "abc";
if (!strcmp(i, j))
{
printf("unlike\n");
}
if (!strcmp(i, k))
{
printf("like\n");
}
}
The string type has been taken from the cs50.h header and strcmp from string.h. strcmp returns value 0 if the two strings are alike and if unlike depending on the alphabetical order returns a positive or negative value. Now if we follow the logic in the previous example, since i and j are unlike, and false it should be reversed to true and unlike should be the output. But I tried running the code and the result was like.
I am confused. Can anyone please explain this to me clearly? Feel free to use other examples too. I could always get away with not using ! but I just want to learn what it is and how to properly use it.
A boolean in C is an integer with zero for false and non-zero for true.
strcmp returns 0 when the compared strings are identical and a non-zero value depending on the difference otherwise. Therefore, strcmp(i,k) is seen as "false". The ! then changes this to "true", which leads to your current output.
In the first case a = 5. then if (!(a == 6)); here a = 6 is not true (false), so it's something like this. if (!(false)) it means if (true). That's why it prints "unlike".
strcmp(i, j) returns 0 if the strings i and j match; otherwise, it will return a non-zero value. In your case,
(!strcmp(i, j))
Here i and j are not equal so strcmp will return a non-zero value because i != j. So !(1) means not(1) means 0, so the if condition is false because of zero. Therefore it'll not execute the printf("unlike\n") line.
(!strcmp(i, k))
Here i and k are same so strcmp will return 0. !(0) means not(0) = 1 so the if condition is true. It will execute the printf("like\n") line.

how will this statement execute conditional operation in c?

i have conditional operator's statement and i have no idea how its works.
there are two questions:
Question 1 : what will the following statement do :
quotient=(b==0)?0:(a/b) \\ here a,b,quotient is integer
Question 2 : Can preceding statement be written as follow ?
quotient=(b)?(a/b):0;
NOW MY QUESTION IS :
Question:1 :: we do not know b's value then how can we check this condition(b==0)
Question 2:: what (b) indicate ?
The conditional check in the C ternary conditional operator is an implicit comparison to not-zero.
In other words
quotient = b ? a / b: 0;
is the same as
quotient = b != 0 ? a / b : 0;
or the absurd
quotient = (b != 0) != 0 ? a / b : 0;
This is consistent throughout C, e.g. in an if, a for stopping condition, a while, &&, ||, &c.
If you try
int b = 0;
if (b) {
printf("Hello World");
}
Does not print anything while :
int b = 1;
if (b) {
printf("Hello World");
}
Prints Hello World. Why ? Because 0 is false and 1 is true.
If you do quotient=(b)?(a/b):0; it is interpreted to is b true ? or in other words is b evaluated to 1 (while, again, 1 is true and 0 is false)
C did not originally have a Boolean type. Conditionals are simply int values in C. 0 is false, and any other value is truthy. If the type of b is int, or it can implicitly convert to int, then (b) ? foo : bar does the same thing as (b == 0) ? bar : foo. (However, b==0 will evaluate to 1 or 0, whereas b by itself might have other nonzero values that if or ? consider truthy.)

Pre-Processor C Macro Syntax

I am trying to understand the Pre-Processor syntax. Its really simple line of code that either returns "ON" or "OFF". However I am utterly confused as to what exactly the condition is?
I understand C's conditional statement as follows:
? x : y
If Condition ? return - replace? x : or y either way this line of code is as follows:
#define ONOFF(a) ((a) ? "ON" : "OFF")
I don't understand what condition must be met here? Is the condition that a has to be something other than null?
True and Flase can be more perfectly presented as 1 or 0 . As I can see you have declared
#define ONOFF(a) ((a) ? "ON" : "OFF")
Your condition here is (a), which istrueif the value ofa is non zero and false if ais 0
Which means in your program, if you write
int a=1;
char *str;
str=ONOFF(a);
The substitution which takes place is
int a=1;
char *str;
str=((a) ? "ON" : "OFF")// here a=1
Since here a is 1 and
1 is true and str gets the value ON. If a were 0, then str would get the value OFF
The condition is that a has to evaluate to true. In c, that means that a must be an expression that is non-zero.
If a is a pointer type, NULL is false and any other value is true.
If a is an integer type, 0 is false and any other value is true.
If a is a floating point type, 0 is false and any other value is true.
If a is a struct or a void type you will get a compile error.
To add a bit of context here, the first operand of the conditional operato has to be of scalar type. Now, from chapter §6.2.5, of C11,
Arithmetic types and pointer types are collectively called scalar types.
So, for the conditional expression,
any non-zero value gets evaluated as TRUE and zero (0) is evaluated as FALSE.
(In case of pointers) a NULL is FALSE, any non-NULL is TRUE.
Preprocessor macros do textual substitution, so a is not a variable -- it's just a placeholder for whatever text is in the parentheses when the macro is used.
You could use it for checking pointers are not null like this:
printf("%s\n", ONOFF(ptr));
printf("%s\n", ONOFF(ptr != null)); // This is the same
Or any other type of condition you like:
printf("%s\n", ONOFF(a > b));
printf("%s\n", ONOFF(a && b));
printf("%s\n", ONOFF(a == 1 || c == 4));
printf("%s\n", ONOFF(somefunction() != 0));
printf("%s\n", ONOFF((a == b && c == d) || (a == c && b == d));
printf("%s\n", ONOFF(my_bool_value));

Statement with ? in C [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
How do I use the conditional operator?
I’m new to C language, and in one of the sample codes I was reviewing I faced the statement:
A = A ? B: C[0]
I was just wondering what the task of the previous statement is and what will be the result after execution of the mentioned statement.
It's called a ternary operator. expr ? a : b returns a if expr is true, b if false. expr can be a boolean expression (e.g. x > 3), a boolean literal/variable or anything castable to a boolean (e.g. an int).
int ret = expr ? a : b is equivalent to the following:
int ret;
if (expr) ret = a;
else ret = b;
The nice thing about the ternary operator is that it's an expression, whereas the above are statements, and you can nest expressions but not statements. So you can do things like ret = (expr ? a : b) > 0;
As an extra tidbit, Python >=2.6 has a slightly different syntax for an equivalent operation: a if expr else b.
It assigns to A the value of B if A is true, otherwise C[0].
?:
result = a > b ? x : y; is identical to this block:
if (a > b) {
result = x;
}
else
{
result = y;
}
It's the same as an if else statement.
It could be rewritten as:
if ( A != 0 )
{
A = B;
}
else
{
A = C[ 0 ];
}
A gets assigned to B if A exists (not NULL), otherwise C[0].
if A equal 0 then A = C[0] else A = B

Resources