Can someone explain what the exclamation point in the if statement does (i.e. !strmcp)?
string names[] = {"EMMA", "RODRIGO", "BRIAN", "DAVID"};
// Search for EMMA
for (int i = 0; i < 4; i++)
{
if (!strcmp(names[i], "EMMA"))
{
printf("Found\n");
return 0;
}
}
printf("Not found\n");
return 1;
For an if statement, if the expression evaluates to 0, then the block of code following the if statement is not executed. Any other value (positive or negative), will result in executing the code block. The function strcmp uses 0 to say that strings are equal because less than 0 is used to differ from greater than 0.
So in this code, we want printf("Found\n"); to be executed when the strings are equal. Since strcmp results in 0, we need to negate the value so that it becomes 1 which will result in executing that code block.
strcmp() returns 0 if the strings are identical, so you need to negate it, if you use it in an if clause to assert a true statement.
If your clause is if(0), the code inside the condition will not be executed.
For completion, it returns negative if the first different character found is lower in the first string, for instance:
first parameter string: "abca"
second parameter string :abcd"
This will return negative. If it's the other way arround it will return positive.
Also, string is not usually used in C (I refer you to Jonathan Leffler's commment), you can use char*:
char *names[] = {"EMMA", "RODRIGO", "BRIAN", "DAVID"};
Unary operator ! is called the logical NOT operator (cf., for example, this definition at cppreference.com). ! expression returns 1 if expression evaluates to 0, and it returns 0 if expression evaluates to anything else but 0.
So the condition in if (!0) gives 1; this means, the condition is met and the if-block is entered. It has the same meaning as if(0==0)
Consequently, the meaning of
if(!strcmp(names[i], "EMMA"))
in your code is exactly the same as
if(0==strcmp(names[i], "EMMA"))
And you already know when strcmp returns 0...
The exclamation point is the C's boolean negation character.
It means give me the boolean opposite of the value. A boolean is either true or false, which are 1 or 0 in the C Language.
In C, if statements execute their conditional statements if the argument is true.
if (a) means if a is true (i.e. non-zero)
if (!a) means if a is false (i.e. 0)
Therefore:
if (a) is the same as if (a != 0)
if (!a) is the same as if (a == 0)
Sometimes you'll see code that uses two exclamation points in a row "!!"
For example:
int a = !!b;
That ensures a will be ONLY 0 or 1, regardless of what the value of b is.
If b is ANY non-zero value, the ! operator will treat it as though it is true true, which it treats as being the same as 1
So:
!0 == 1
!1 == 0
!52 == 0
!25692 == 0
The second ! does the boolean inversion again, so:
!!0 == 0
!!1 == 1
!!52 == 1
!!25692 == 1
In C any non zero value is considered ad the logical truth, zero i considered as logical false. ! is a logical negation. So !0 (not false) will be the truth and if(!strcmp(str1,str2)) {statements} statements will be executed when str1 will be same as str2
Related
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.
for(i=1;i=-1;i++)
if(i<5) break;
printf("%d\n",i);
i was asked to write the output of the following code, i could not understand as the second argument should have been a condition, but here it was an assignment,
output: -1
i cant understand how it is possible, so i tried to experiment with the code
int i=1;
while(i=-1)
{
printf("condition is true\n");
if(i<5) break;
}
printf("%d\n",i);
the output of the following code is
output: condition is true
-1
can anyone explain how the above two codes work
and how is while(i=-1) evaluated to TRUE??
The condition is always true. Because the value of an assignment statement is the value assigned. So -1 is non-zero and non-zero value is considered as true in c so it is always true.
The correct usage would be == which compares the value and returns 1 or 0 based on the equality or non-equality.
So here when you did i = -1 and put in the while loop condition - it boils down to
while( -1 ){
...
/* break here */
}
And as -1 is considered as true in c because of it being nonzero - the loop condition evaluates to true.
The break statement here is given here so that this loop doesn't turn to be an infinite loop.
The syntax of a for loop in C is
for(expr1, expr2; expr3)
/* body of loop */
Now, conventionally, expr1 is the loop initialization, and expr2 is the condition under which to keep going, and expr3 is the increment between loops. But that's only a convention -- in actuality, the compiler just arranges to execute expr1 once, then expr2 to decide whether to take another trip through the loop or not, then expr3 at the bottom of the loop. So it's more or less equivalent to
expr1;
while(expr2) {
/* body of loop */
expr3;
}
Or, stated another way:
expr1;
while(1) {
if(!expr2) break;
/* body of loop */
expr3;
}
But then the other key point is that, yes, the expression
i = -1
doesn't look much like a condition; it looks like an assignment. But in C, when you use an expression as a condition (that is, in a context where what we care about is whether the expression is "false" or "true", all we really care about is whether the expression evaluates to zero or to non-zero. And the value of an assignment expression is simply the value that was assigned. So the value of
i = -1
is -1, and that's not zero, so it's interpreted as "true". So if you say
while(i = -1) {
/* body of loop */
}
the condition is always "true", so it will be an infinite loop, unless there's a break statement in the body somewhere (or a return, or a call to exit(), or something like that).
First for loop one does nothing and will be removed from the generated code if the optimisation is on
Second one enters the loop one time. The actual loop will be removed by the optimising compiler and replaced by the puts, initialisation and printf call.
https://godbolt.org/g/T5wgqt
printf with the format string only is replaced by the puts
I came across this line of code written in C that confuses me coming from a JavaScript background.
short s;
if ((s = data[q]))
return s;
Is this assigning s to data[q], and if it equals true/1, return s?
Yes, an assignment...well assigns...but it's also an expression. Any value not equalling zero will be evaluated as true and zero as false.
it would be the same as
if ((s = data[q]) != 0) return s;
Your code is assigning data[q] to s and then returns s to the if statement. In the case when s is not equal to 0 your code returns s otherwise it goes to the next instruction.
Or better said it would expand to the following:
short s;
s = data[q];
if (s != 0)
return s;
Basically C evaluates expressions. In
s = data[q]
The value of data[q] is the the value of expression here and the condition is evaluated based on that.
The assignment
s <- data[q]
is just a side-effect.
Read this [ article ] on sequence points and side-effects
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));
In C language, what is the result of x=0 if I put it in if-else condition? if it is represent false or if this assignment is finished, then represent true?
my colleague write code as:
if(condition = 0)
{
//do process A
}
else
{
// do process B
}
obviously, this code is wrong, I know it should be condition == 0 or ((condition=foo()) == 0) but my assumption is program should always do process A because i think if(condition = 0) should always return true since this is set value 0 to variable condition and this set process should be true. However, program always do process B, that means if use the variable condition value and my assumption is wrong.
Then I did a another test code:
if(condition = 2) //or other none-zero value
{
//do process A
}
else
{
// do process B
}
this time, program always do process A.
My question is why if-else condition does not use the operation value of condition but use the left variable after setting?
when you assign 0 to variable condition it becomes false as 0 represents false and any non-zero value represents true.so, when you assign 0 else condition is executed and when you assign 2 condition represents a true statement so, it executes...
if(condition = 0)
after assigning value 0 to condition it becomes
if(condition)
and as it is false, it doesn't execute.but, when condition = 2, it works in the same way and become true .so, the if condition is executed then.
You use wrong operator.
a = 10;
The "equals" operator means "assign value to".
Now to compare two operands, a and b, to see if a = b, you use another operand.
That operand is double equals (==).
if(variable == 0)
{
//do process A
}
else
{
// do process B
}
Now look.
If the variable with name "variable" has value = 8 that is not equal to 0,
thus the whole "variable == 0" expression if FALSE.
So proccess B will run.
If otherwise variable is equal to 0 indeed, proccess A will be executed because "variable == 0" is true.
It's like:
if(EXPRESSION)
{
// EXPRESSION IS TRUE
}
else
{
//EXPRESSION IS FALSE
}
Got it? :)
In C, assignment is an expression that returns the set value; i.e. x = 2 will result in 2.
This allows you to do something like this:
unsigned char ch;
while((ch = readFromFile(f)) != EOF) {
// do something with ch
}
It also allows you to shoot yourself in the foot if you accidentally mistype == as =, which is why this 'feature' doesn't appear in a lot of other languages.
In your first loop, the expression condition = 0 will always result in 0, causing the else branch to be taken. Similarly, condition = 2 results in 2, which causes the true branch to be taken.