While Loop and Logical Operations - c++

I want to use one AND operator and 2 OR operators combined in a While loop, but I am getting an error in CPP.
while(vLessonNames.size>=1 && (log=='Y' || log=='y'))
I want to proceed when vector size is one or greater and log = Y or y
Error: invalid use of member (did you forget the '&' ?)|

I think your problem is that .size might be a function. So try to rewrite the statement like:
while( ( (vLessonNames.size() >=1) && (log=='Y' || log=='y') ) )
{...}

Related

Avoiding incrementing in if statement in C++

I would like to avoid incrementing and decrementing in if-statement since there is a segmentation fault error in the following code while checking conditions (if we start with p = 1 and k = 1 for example):
if (((heights[k--][p--] < heights[k][p]) || (heights[k--][p--] == heights[k][p])) &&
((heights[k--][p++] < heights[k][p]) || (heights[k--][p++] == heights[k][p])) &&
((heights[k++][p--] < heights[k][p]) || (heights[k++][p--] == heights[k][p])) &&
((heights[k++][p++] < heights[k][p]) || (heights[k++][p++] == heights[k][p]))){
width[k][p] = 3;
}
For example, the second check fails with k = -1.
I would like to check neighbouring elements of a two-dimensional array heights in an if-statement and than run some logic in case it was true.
How can I optimise it and generally rewrite it to make it look (and work) better? I haven't found any information on it.
As others have indicated, replacing 'k--' with 'k-1' and 'k++' with 'k+1' for all 'k' and 'p' variables may resolve the segmentation error. 'k+1' is a reference to the next array index after 'k', while 'k++' increments the value of 'k' after it's used. It's also good programming practice to avoid using expressions as arguments.
https://en.cppreference.com/w/cpp/language/operator_incdec
To clean up the code, you could also simplify the logical OR by replacing '<' with '<='.
if ((heights[k-1][p-1] <= heights[k][p]) &&
(heights[k-1][p+1] <= heights[k][p]) &&
(heights[k+1][p-1] <= heights[k][p]) &&
(heights[k+1][p+1] <= heights[k][p])){
width[k][p] = 3;
}

Find a logical expression that is true if `n` is a multiple of `2019` and is not in the interval `(a, b)`

I had the task of finding a logical expression that would result in 1 if and only if a given number n is a multiple of 2019 and is NOT from the interval (a, b).
The textbook gave the following answer and I don't really understand it:
a>=n || b<=n && (n%3==0 && n%673==0)
The thing between those parantheses I understand to be equivalent to n%2019==0, so that's alright. But I don't understand why this works, I mean the && operator has higher priority that the || operator, so wouldn't we evaluate
b<=n && (n%3==0 && n%673==0)
first and only at the end if n<=a? I thought that if I were to do it, I would do it like this:
(a>=n || b<=n) && (n%3==0 && n%673==0)
So I just added that extra set of parantheses. Now we would check if the number is not in the interval (a, b), then we would check if it is a multiple of 2019 and then we would 'and' those to answers to get the final answer. This makes sense to me. But I don't understand why they omitted that set of parantheses, why would that still work? Shouldn't we consider that && has higher priority than ||, so we add an extra set of parantheses? Would it still work? Or is it me that is wrong?
Trying it out shows that the expression as written without the extra parentheses doesn't work:
bool expr(int n, int a, int b)
{
return a>=n || b<=n && (n%3==0 && n%673==0);
}
expr(1000, 2000, 2018) for example evaluates to true, even though it is not a multiple of 2019.
As you pointed out, the logical AND operator && has higher precedence than the logical OR operator || (reference), so the expression is equivalent to:
a>=n || (b<=n && (n%3==0 && n%673==0))
which is always true when n <= a, even if it's not a multiple of 2019.
A clearer expression would be:
(n % 2019 == 0) && (n <= a || n >= b)

Operator Precedence

I have a sample midterm question that I am not too sure about. Here it is:
#include <iostream.h>
void f( int i )
{
if( i = 4 || i = 5 ) return;
cout << "hello world\n" ;
}
int main()
{
f( 3 );
f( 4 );
f( 5 );
return 0;
}
So I understand that the logical OR operator has a higher precedence and that it is read left to right. I also understand that what's being used is an assignment operator instead of the relational operator. I just dont get how to make sense of it all. The first thing the compiler would check would be 4 || i? How is that evaluated and what happens after that?
Let's add all the implied parentheses (remembering that || has higher precedence than = and that = is right-associative):
i = ((4 || i) = 5)
So, it first evaluates 4 || i, which evaluates to true (actually, it even ignores i, since 4 is true and || short-circuits). It then tries to assign 5 to this, which errors out.
As written, the code doesn't compile, since operator precedence means it's i = ((4 || i) = 5) or something, and you can't assign to a temporary value like (4 || i).
If the operations are supposed to be assignment = rather than comparison == for some reason, and the assignment expressions are supposed to be the operands of ||, then you'd need parentheses
(i = 4) || (i = 5)
As you say, the result of i=4 is 4 (or, more exactly, an lvalue referring to i, which now has the value 4). That's used in a boolean context, so it's converted to bool by comparing it with zero: zero would become false, and any other value becomes true.
Since the first operand of || is true, the second isn't evaluated, and the overall result is true. So i is left with the value 4, then the function returns. The program won't print anything, whatever values you pass to the function.
It would make rather more sense using comparison operations
i == 4 || i == 5
meaning the function would only print something when the argument is neither 4 nor 5; so it would just print once in your example, for f(3).
Note that <iostream.h> hasn't been a standard header for decades. You're being taught an obsolete version of the language, using some extremely dubious code. You should get yourself a good book and stop wasting time on this course.
The compiler shall isuue an error because expression 4 || i is not a lvalue and may not be assigned.
As for the expression itself then the value of it is always equal to true because 4 is not equal to zero.

c++ what is the correct syntax here?

what is the correct syntax for checking a varable value and then setting a varable in the same condition also checking that new set varables var, all in one if statement?
so basically something like
if(this->somevar > 0 && this->newvar = this->GetNewVar(this->somevar),this->newvar > 0)
i know that is not the correct syntax or at least its not working for me anyway, hence the topic, i am using that as an example, so if this->somevar is null or 0, i don't want it to execute the next condition which is && this->newvar = this->GetNewVar(this->somevar,this->newvar but instead skip the statement and ignore that part.
what is the correct syntax for something like this?
&& is an operator with short circuit evaluation, right part is not executed if left part is true.
But why don't you simply write:
if(this->somevar > 0)
{
this->newvar = this->GetNewVar(this->somevar);
if (this->newvar > 0)
{
...
This will certainly makes things clearer ...
the logical AND && operator is short-circuited if this->somevar evaluates to zero, meaning the rest of your if expression would not be evaluated in that situation
The expression after the comma is not necessary. Also, there is one thing missing, parentheses arround the assignment:
if(this->somevar > 0 && (this->newvar = this->GetNewVar(this->somevar)) > 0)
Without the parentheses you may end up setting this->newvar to the value of the boolean expression
this->GetNewVar(this->somevar),this->newvar > 0, which will be evaluated to a boolean result (true/false which, in turn, may be converted to 0 or 1 or -1 depending on the compiler, when cast to the type of this->newvar).
I think only the bit after the comma is evaluated for the if condition. The expression on the left of the comma is ignored.
int main() {
if( false, true) { cout << " got to if( false, true ) "; }
if ( true, false ) { cout << "got to if( true, false ) "; }
}
to answer your question, you can put anything on the left of the comma and do whatever you like, as long as the expression you want to evaluate is the last expression in the list.
so if ( exp1, exp2, exp3 , exp4 ) dowhatever(); only gets run if exp4 is true. You should really run exp1 to exp3 outside the if condition for readability.

Best way to format if statement with multiple conditions

If you want to some code to execute based on two or more conditions which is the best way to format that if statement ?
first example:-
if(ConditionOne && ConditionTwo && ConditionThree)
{
Code to execute
}
Second example:-
if(ConditionOne)
{
if(ConditionTwo )
{
if(ConditionThree)
{
Code to execute
}
}
}
which is easiest to understand and read bearing in mind that each condition may be a long function name or something.
I prefer Option A
bool a, b, c;
if( a && b && c )
{
//This is neat & readable
}
If you do have particularly long variables/method conditions you can just line break them
if( VeryLongConditionMethod(a) &&
VeryLongConditionMethod(b) &&
VeryLongConditionMethod(c))
{
//This is still readable
}
If they're even more complicated, then I'd consider doing the condition methods separately outside the if statement
bool aa = FirstVeryLongConditionMethod(a) && SecondVeryLongConditionMethod(a);
bool bb = FirstVeryLongConditionMethod(b) && SecondVeryLongConditionMethod(b);
bool cc = FirstVeryLongConditionMethod(c) && SecondVeryLongConditionMethod(c);
if( aa && bb && cc)
{
//This is again neat & readable
//although you probably need to sanity check your method names ;)
}
IMHO The only reason for option 'B' would be if you have separate else functions to run for each condition.
e.g.
if( a )
{
if( b )
{
}
else
{
//Do Something Else B
}
}
else
{
//Do Something Else A
}
Other answers explain why the first option is normally the best. But if you have multiple conditions, consider creating a separate function (or property) doing the condition checks in option 1. This makes the code much easier to read, at least when you use good method names.
if(MyChecksAreOk()) { Code to execute }
...
private bool MyChecksAreOk()
{
return ConditionOne && ConditionTwo && ConditionThree;
}
It the conditions only rely on local scope variables, you could make the new function static and pass in everything you need. If there is a mix, pass in the local stuff.
if ( ( single conditional expression A )
&& ( single conditional expression B )
&& ( single conditional expression C )
)
{
opAllABC();
}
else
{
opNoneABC();
}
Formatting a multiple conditional expressions in an if-else statement this way:
allows for enhanced readability:
a. all binary logical operations {&&, ||} in the expression shown first
b. both conditional operands of each binary operation are obvious because they align vertically
c. nested logical expressions operations are made obvious using indentation, just like nesting statements inside clause
requires explicit parenthesis (not rely on operator precedence rules)
a. this avoids a common static analysis errors
allows for easier debugging
a. disable individual single conditional tests with just a //
b. set a break point just before or after any individual test
c. e.g. ...
// disable any single conditional test with just a pre-pended '//'
// set a break point before any individual test
// syntax '(1 &&' and '(0 ||' usually never creates any real code
if ( 1
&& ( single conditional expression A )
&& ( single conditional expression B )
&& ( 0
|| ( single conditional expression C )
|| ( single conditional expression D )
)
)
{
... ;
}
else
{
... ;
}
The first example is more "easy to read".
Actually, in my opinion you should only use the second one whenever you have to add some "else logic", but for a simple Conditional, use the first flavor. If you are worried about the long of the condition you always can use the next syntax:
if(ConditionOneThatIsTooLongAndProbablyWillUseAlmostOneLine
&& ConditionTwoThatIsLongAsWell
&& ConditionThreeThatAlsoIsLong) {
//Code to execute
}
Good Luck!
The question was asked and has, so far, been answered as though the decision should be made purely on "syntactic" grounds.
I would say that the right answer of how you lay-out a number of conditions within an if, ought to depend on "semantics" too. So conditions should be broken up and grouped according to what things go together "conceptually".
If two tests are really two sides of the same coin eg. if (x>0) && (x<=100) then put them together on the same line. If another condition is conceptually far more distant eg. user.hasPermission(Admin()) then put it on it's own line
Eg.
if user.hasPermission(Admin()) {
if (x >= 0) && (x < 100) {
// do something
}
}
The second one is a classic example of the Arrow Anti-pattern So I'd avoid it...
If your conditions are too long extract them into methods/properties.
The first one is easier, because, if you read it left to right you get:
"If something AND somethingelse AND somethingelse THEN" , which is an easy to understand sentence. The second example reads "If something THEN if somethingelse THEN if something else THEN", which is clumsy.
Also, consider if you wanted to use some ORs in your clause - how would you do that in the second style?
In Perl you could do this:
{
( VeryLongCondition_1 ) or last;
( VeryLongCondition_2 ) or last;
( VeryLongCondition_3 ) or last;
( VeryLongCondition_4 ) or last;
( VeryLongCondition_5 ) or last;
( VeryLongCondition_6 ) or last;
# Guarded code goes here
}
If any of the conditions fail it will just continue on, after the block. If you are defining any variables that you want to keep around after the block, you will need to define them before the block.
I've been facing this dilemma for a long time and I still can't find a proper solution. In my opinion only good way is to first try to get rid of conditions before so you're not suddenly comparing 5 of them.
If there's no alternative then like others have suggested - break it down into separete ones and shorten the names or group them and e.g. if all must be true then use something like "if no false in array of x then run".
If all fails #Eoin Campbell gave pretty good ideas.
When condition is really complex I use the following style (PHP real life example):
if( $format_bool &&
(
( isset( $column_info['native_type'] )
&& stripos( $column_info['native_type'], 'bool' ) !== false
)
|| ( isset( $column_info['driver:decl_type'] )
&& stripos( $column_info['driver:decl_type'], 'bool' ) !== false
)
|| ( isset( $column_info['pdo_type'] )
&& $column_info['pdo_type'] == PDO::PARAM_BOOL
)
)
)
I believe it's more nice and readable than nesting multiple levels of if(). And in some cases like this you simply can't break complex condition into pieces because otherwise you would have to repeat the same statements in if() {...} block many times.
I also believe that adding some "air" into code is always a good idea. It improves readability greatly.