Condition with OR operator - if-statement

I have a condition Javascript like that :
if(a!= undefined || b!= undefined){
do something
}
if the a value is undefined I can't enter the condition (that's good) but if the a value is not undefined BUT the b value is undefined, I still enter in the condition...

You need to have an AND condition:
if (a != undefined && b != undefined) {
do something
}

Related

Why does (0 && 1 == 0) not evaluate to true?

In my if statement, the first condition for && is 0 (false), so the expression 0 && (a++) is equal to 0, right? Then 0==0 it should be true. Why am I getting else here? Please explain!
int a=0;
if(0 && (a++)==0)
{
printf("Inside if");
}
else
{
printf("Else");
}
printf("%i",a);
The == operator has a higher priority than the && operator, so this line:
if(0 && (a++)==0)
is treated like this:
if( 0 && ((a++)==0) )
So the whole expression under the if is false, and a++ is not even evaluated due to short circuitry of the && operator.
You can read about Operator Precedence and Associativity on cppreference.com.
When in doubt, you should use parenthesis to express your intention clearly. In this case, it should be:
if( (0 && (a++)) == 0 )
Though, it does not make any sense, as it always evaluates to true and a++ is not incremented here, either.
As already mentioned, the precedence of == is higher than precedence of &&, so the statement is resolved into
if( 0 && ((a++)==0))
However, still even if you add the correct order of brackets, a++ returns the original value of a, which is 0, but the a is incremented. If you want to return the updated value of a, you should write ++a
if( ((++a) && 0) == 0 )
Although the question seems easy it's very error-prone.
We need to know the precedence of various operators involved in this.
1. postfix (++)
2. ==
3. Logical AND (&&)
the final expression can be seen as: if ( (0 && (a++)) == 0 )
which is true. Hence statement under if is evaluated to be true.

How do I get multiple conditions within one while loop?

I am using a while loop and I want to user to input r, R, p, or P. But when I add more than one condition like:
while ((userInput != "r") || (userInput != "p" || (userInput != "R") || (userInput!= "P")) {
cout << "Please enter a valid option" << endl;
cin >> userInput;
}
my program will forever be stuck in the loop. Where as if I input it like this:
while (userInput != "r") {
cout << "Please enter a valid option" << endl;
cin >> userInput;
}
Then my code will exit the for loop if user inputs "r"
So why does the first block of code not work? I have no errors, which means it has to be a logical error but I do not understand. How can I get more thano ne condition in a for loop and make it work?
You need to use && instead of || because using || the condition in the while is always true. When you write “r”, for example, the condition userinput != r is false but the rest are true, with && all the expressions turn to false and the while ends.
Why does the above condition not work?
The reason is because if you say x is not 3 or x is not 5, then if x is 3, then x is not 5, so the entire statement evaluates to true. Your different userInput != 'r' and userInput != 'p' are just like that situation with the x.
To show it simpler, I'll show a truth table for or. When the expression evaluates to true, your while loop would continue below those circumstances, where p and q are statements that may be true or false like userInput != 'r'.
|| -- or
q\p|_T_|_F_|
_T_|_T_|_T_|
_F_|_T_|_F_|
Meaning that with an or clause, the only way it's false is if all parts are false.
An And clause appears to be what you want. It's truth table is:
&& -- and
q\p|_T_|_F_|
_T_|_T_|_F_|
_F_|_F_|_F_|
Meaning, that with an and clause, the only way for it to be true is if all clauses are true.
So if you want the response to be neither r nor p nor R nor P, etc, use && for and:
while ((userInput != "r") && (userInput != "p") && (userInput != "R") && (userInput!= "P")) {
And then the while loop will exit as soon as userInput does not match any of r, p, R or P. This is because as the program evaluates, it checks:
With the example of userInput as "g":
Does the userInput g equal r? No. So the first clause is True. Does the userInput g equal p? No. So the second clause is True. Does the userInput g equal R? No. So the third clause is True. Does the userInput g equal P? No. So the fourth clause is True. Since all four are true, then the whole statement is true, and the while loop continues.
With the example of userInput as "R":
Does the userInput g equal R? No. So the first clause is True. Does the userInput g equal R? No. So the second clause is True. Does the userInput g equal R? YES. So the third clause is False. Since a part of the statement is false, the whole and clause is false, so the while loop exits.

Integer to Boolean strange syntax [duplicate]

This question already has an answer here:
The Definitive C++ Book Guide and List
(1 answer)
Closed 7 years ago.
I'm less than a year into C++ development (focused on other languages prior to this) and I'm looking at a guy's code who's been doing this for two decades. I've never seen this syntax before and hopefully someone can be of some help.
bool b; // There exists a Boolean variable.
int i; // There exists an integer variable.
sscanf(value, "%d", &i); // The int is assigned from a scan.
b = (i != 0); // I have never seen this syntax before.
I get that the boolean is being assigned from the int that was just scanned, but I don't get the (* != 0) aspects of what's going on. Could someone explain why this person who knows the language much better than I is doing syntax like this?
Have a read here:
http://en.cppreference.com/w/cpp/language/operator_comparison
The result of operator != is a bool. So the person is saying "compare the value in i with 0". If 'i' is not equal to 0, then the '!=' returns true.
So in effect the value in b is "true if 'i' is anything but zero"
EDIT: In response to the OP's comment on this, yes you could have a similar situation if you used any other operator which returns bool. Of course when used with an int type, the != means negative numbers evaluate to true. If > 0 were used then both 0 and negative numbers would evaluate to false.
The expression (i != 0) evaluates to a boolean value, true if the expression is true (i.e. if i is non-zero) and false otherwise.
This value is then assigned to b.
You'd get the same result from b = i;, if you prefer brevity to explicitness, due to the standard boolean conversion from numeric types which gives false for zero and true for non-zero.
Or b = (i != 0) ? true : false; if you like extraneous verbosity.
(i != 0) is an expression that evaluates to true or false. Hence, b gets the value of true/false depending on the value of i.
This is fairly fundamental syntax. The != operator performs a "not equal to" comparison.
You may be being confused by the shorthand of initialising a bool directly from the result of a comparison operator, but the syntax itself is not esoteric.
The program is essentially equivalent to:
bool b;
int i;
sscanf(value, "%d", &i);
if (i != 0)
b = true;
else
b = false;
The key is that i != 0 is itself an expression that evaluates to true or false, not some magic that may only be used in an if statement.
Basically, if the condition (i not_equal_to 0 ) is satisfied, b gets the value "true". Else b gets the value "false".
Here, "i != 0" is a boolean expression that will be true if "i" is non-zero and false if it is zero.
All that is happening here is the result of that expression is being assigned to a variable.
You could also do things like...
boolean canDrinkAlcohol = (person.age() >= 18 && person.country.equals("UK") || person.age() >= 21 && person.county.equals("US"));
...
if(canDrinkAlcohol) {
...
}
or something

c++ need help to understand

So I have this piece of code.
I understand all the things beside the fact that when does the loop actually take place again. I mean what is meant by the e(!valid) statement. Does it refer to its numeric value or what? Can somebody please explain this to me. Consider all required variable declared. And ignore uppercase.
The code is:
do
{
valid=1;
gotoxy(22,7);
gets(emailid);
int flag=0;
for (int i = 0; emailid[i] != '\0'; i++)
if (emailid[i] == '#')
flag++;
If(!flag)
{
valid = 0;
cout << "not a valid id. Try again";
getch();
}
} while(!valid);
So mainly I want to know that it is working, with emphasis on what does !valid and !fail mean.
From what I could get, it has to do with its numeric values but I am still confused.
To answer the question:
} while (!valid);
means: treat the integer behind valid as a boolean. (assuming it is an integer, as it was given a value of 1)
i == 0 -> false
i != 0 -> true
!valid:
valid == 0 -> true
valid != 0 -> false
In C++ the value 0 is considered "false" and any other integer is considered "true". In this case while valid is equal to 0 the loop runs.
Numeric value can be promoted to bool type this way:
Zero means false and other values mean true. So !valid will return true only if valid == 0.
What it means is your do while() loop will repeat itself until valid equals value other than 0.

Linear Search in Linked List [Language: C++ Compiler: Dev-Cpp 4.9.9.2]

I'm having a problem and can't seem to find the solution..
int linearSearch(nodeptr list,char search){
int pos =0;
if(list==NULL)
return -1;
while(list->info!=search && list!=NULL){
pos++;
list=list->next;
}
if(list==NULL)
return -1;
else
return pos;
}
I always get a runtime error.. :(
while(list->info!=search && list!=NULL)
should be:
while(list!=NULL && list->info!=search)
This is called as Short-circuit evaluation.
When you use && the first expression is guaranteed to be executed before the second for inbuilt primitive types[#1].
In your case the dereferencing happens before the NULLcheck, So when list == NULL, You will end up derefrencing the NULLand causing an Undefined Behavior and a crash.
In the sugeested solution:
if list == NULL then the second condition will not be evaluated.
Reference:
[#1]C++03 Standard 1.9.18:
In the evaluation of the following expressions
a && b
a || b
a ? b : c
a , b
using the built-in meaning of the operators in these expressions, there is a sequence point after the evaluation of the first expression (12).
you are not checking for the validity of list here:
while(list->info!=search && list!=NULL)
try checking list!=NULL before list->info.
Also, don use the name list, it is the name of a standard library container.
&& conditions are evaluated in the order they are specified, so in you case when list becomes NULL in the loop during the next iteration you are first trying to do list->info != search which results in access violation. You need to reverse the condition to list != NULL && list->info != search.