I am trying to figure out what is going on with the "and" statements in the return line from this sample of code, could someone please tell me what the purpose of putting these "and" statements in the return of a function is?
if just one of them is false would it return false to the function that called it?
return !UsedInRow(board, row, num) && !UsedInCol(board, col, num) &&
!UsedInBox(board, row - row % 3 , col - col % 3, num);
It's equivalent to
bool a;
a = UsedInRow(board, row, num);
if (a) return false;
a = UsedInCol(board, col, num);
if (a) return false;
a = UsedInBox(board, row - row % 3 , col - col % 3, num);
if (a) return false;
return true;
due to the short-circuiting nature of the && and the fact that evaluation is from left to right.
(This holds true even if the function parameters are passed by reference and modified in the functions, as && is a sequencing point.)
if just one of them is false would it return false to the function that called it? The answer is yes.
This will stop the computation of further functions as False AND any value => False.
This will return True or False based on the values returned by the UsedIn* functions.
This is to check whether the number 'num' can be inserted in Suduko. This will check whether the number can be inserted in a given cell provided it is present in that row, column or the box.
UsedInRow and UsedInCol are both functions returning a bool (or a type that can be converted to bool). The && operators just chain the return values of the functions together that results into a final bool result that yields either true or false which is then returned.
Note that not all functions in this case have to run because of short-circuit evaluation, that is, if the result one of the three boolean expressions is false then (because of the &&) the result can't possibly be true and thus functions that are not yet evaluated won't be evaluated.
Yes, it works exactly like in an if statement. If any of the Used functions return true then the whole return value will evaluate to false.
if !UsedInRow(board, row, num) this executes to return false then return statement will automatically return flase without executing other two statements
if !UsedInRow(board, row, num) returns true only then second statement !UsedInCol(board, col, num) will get executed and now if it returns false then the return statement will return false otherwise third statement will get executed
Now if !UsedInBox(board, row - row % 3 , col - col % 3, num) this statement evaluates to be true return statement will return true else it will return false
So in order to get true from return statement all three conditions should be evaluated to get true value
The && operator returns a bool value (true or false) so the expression is equivalent to:
if (!UsedInRow(board, row, num) && !UsedInCol(board, col, num) &&
!UsedInBox(board, row - row % 3 , col - col % 3, num)
return true;
else
return false;
also you may find some sort of these expressions which also holds the same result:
return (!UsedInRow(board, row, num) && !UsedInCol(board, col, num) && !UsedInBox(board, row - row % 3 , col - col % 3, num))?true:false;
Related
I am learning how to write the comparator in C++. At first time, I return num1<num2, as a result I get a set in ascending order. Then I return num1>num2 and I get a set in descending order. Now I try to return num1-num2 which should equal to num1>num2 in my opinion, I get a set in descending order as predicted. But when I try to return num2-num1, I still get a set in descending order. How could it happen? Is there any difference between return num2-num1 and return num1<num2?
#include <iostream>
#include <set>
using namespace std;
struct myCmp{
bool operator()(const int& num1, const int& num2){
return num2-num1;
}
};
int main()
{
set<int,myCmp> st;
st.insert(1);
st.insert(2);
st.insert(3);
for(auto it=st.begin();it!=st.end();it++){
cout<<*it<<endl;
}
return 0;
}
Now I try to return num1-num2 which should equal to num1>num2 in my opinion
That is incorrect.
Is there any difference between return num2-num1 and return num1<num2?
Yes.
num2-num1 returns an integer value that is the result of subtracting the value of num1 from the value of num2. Since your comparator returns a bool, a result of 0 will be converted to false, and any other result will be converted to true.
num1<num2 returns a boolean value specifying whether or not num1 is actually less-than num2. Any value of num1 that is less-than the value of num2 will return true, all other values will return false.
So, as you can see, both approaches return completely different things.
std::set has the following requirement:
std::set is an associative container that contains a sorted set of unique objects of type Key. Sorting is done using the key comparison function Compare. Search, removal, and insertion operations have logarithmic complexity. Sets are usually implemented as red-black trees.
Everywhere the standard library uses the Compare requirements, uniqueness is determined by using the equivalence relation. In imprecise terms, two objects a and b are considered equivalent if neither compares less than the other: !comp(a, b) && !comp(b, a).
Using return num1<num2 (or return num1>num2) satisfies that requirement, but return num2-num1 breaks it.
For example, let's assume a = 1 and b = 2.
Using num1<num2, you get the following:
!comp(a, b) && !comp(b, a)
= !comp(1, 2) && !comp(2, 1)
= !(1 < 2) && !(2 < 1)
= !true && !false
= false && true
= one is less-than the other, so not equal, which is correct!
Using num1>num2, you get the following:
!comp(a, b) && !comp(b, a)
= !comp(1, 2) && !comp(2, 1)
= !(1 > 2) && !(2 > 1)
= !false && !true
= true && false
= one is less-than the other, so not equal, which is correct!
Using num2-num1, you get the following:
!comp(a, b) && !comp(b, a)
= !comp(1, 2) && !comp(2, 1)
= !(2 - 1) && !(1 - 2)
= !(1) && !(-1)
= !true && !true
= false && false
= neither is less-than the other, so equal, which is incorrect!
I try to return num1-num2 which should equal to num1>num2 in my opinion
Let's try that:
num1 = 5;
num2 = 10;
num1>num2 // false
num1-num2 // -5, true
So, no, your assumption is incorrect. All results when num1 != num2 are converted to true in a boolean context, and only when num1 == num2 will the result be converted to false.
I have a loop going through an array trying to find which index is a string. It should solve for what that value should be.
I can't figure out why, but as soon as the if statements start i becomes 1 which gives my code an error.
I'm not very fluent in C++.
for(int i = 0; i < 4; i++) {
if(auto value = std::get_if<std::string>(&varArr[i])) {
solvedIndex = i;
auto value0 = std::get_if<float>(&varArr[0]);
auto value1 = std::get_if<float>(&varArr[1]);
auto value2 = std::get_if<float>(&varArr[2]);
auto value3 = std::get_if<float>(&varArr[3]);
//i changes to 1 when this if starts??
if(i = 0) {
solvedVar = (*value3 / *value1) * *value2;
} else if (i = 1) {
solvedVar = *value3 / (*value0 / *value2);
} else if (i = 2) {
solvedVar = *value0 / (*value3 / *value1);
} else {
solvedVar = *value1 * (*value0 / *value2);
}
break;
}
}
Note that these variables are declared above. Also, varArr is filled with values:
std::variant<std::string, float> varArr[4];
int solvedIndex;
float solvedVar;
As has been noted, in your if statements, you are using the assignment operator (=) but want the equality comparison operator (==). For your variable i the first if statement sets i equal to 0 and if(0) is the same as if(false). So your program goes to the first else-if which sets i equal to 1 and if(1) evaluates to true. Your code then finishes the block within else if (i = 1) {...} and then ends.
That's because operator= is the assignment operator in C++ (and most languages, actually). That changes the value of the variable to the value on the other side. So, for instance:
x = 0
will change the value of x to 0. Doesn't matter if it's in an if statement. It will always change the value to 0 (or whatever the right hand side value is).
What you are looking for is operator==, which is the comparison (aka relational) operator in C++/ That asks the question "Are these two things equal?" So, for instance:
x == 0
asks is x is equal to 0.
So I have this simple function and it is suppose to return true or false. True is only returned 2% of the time and false every other time. However, whenever I try to compile the full code I get the error message;
'TRUE' was not declared in this scope C++
I am aware I can use int instead of bool and just use 1 for true and 0 for false, but I want to figure out why this won't work. Any help?
Here is my function:
bool Bunny::determineMutant()
{
int rand_num = rand() % 100 + 1; //random num 1-100
if(rand_num == 1 || rand_num == 2) return TRUE;
else return FALSE;
}
TRUE and FALSE are often associated with the Win32 type BOOL, alternatively a macro for the integers 1 and 0. The actual error is there since the definition of TRUE is not available.
For the built in C++ type bool use true and false. I think this should be the preferred solution here.
As a side note, the code could be simplified to return based on the condition in the if() which is already a bool;
return (rand_num == 1 || rand_num == 2);
The keywords in C++ are lowercase true and false.
The all-caps TRUE and FALSE are generally preprocessor macros of 1 and 0 respectively in VC++, and are used to return the type BOOL.
Sorry for this newbie question, but I can't find on google what I need to know.
I understand return, but don't understand this... What does it mean this?
return (tail+1)%N == head%N;
Thanks a lot for patience.
It returns true or false, depending on whether the expression is true or not.
It's the same as:
if ( (tail+1)%N == head%N )
return true;
else
return false;
this
(tail+1)%N == head%N
returns a boolean value, either true or false. This statement means that after adding 1 to trail (trail + 1) and the remainder obtained after division with N is equal to remainder of head divided with N. % is used for division with remainder
(%). Modulo is the operation that gives the remainder of a division of two values.
Check this link for c++ operators : http://www.cplusplus.com/doc/tutorial/operators/
you're returning a boolean value. The value represents whether or not the remainder of (tail+1) divided by N is the same as that of head.
It evaluates the expression, and return the result. In this case it's two modulo operations that are compared, and the result is either true or false which will be returned.
Short Answer:
Because of the == operator your function will return a bool, meaning it can only be trueor false. An equivalent would be something like:
return 5 == 4;
which would return false since 5 is not equal to 4.
Long Answer:
Instead of writing this in a single line you could split it up into more lines of code. Let's just assume that tail, head and N are integer values, then you could write it like this:
int x, y;
x = (tail+1)%N;
y = head%N;
if ( x == y )
{
return true;
}
else
{
return false;
}
Now in this code there may be also that %confuses you a bit. The %is called the Modulus Operator and can give you the remainder of arithmetic operations. In a simple example this would mean:
10 % 3 = 1 because 10/3 is 3 with a remainder of 1. So to make it more clear let's just make another example with your specific problem:
Lets just assume that tail=10,head=6 and N=2. Then you would get something like this:
x = (10+1)%2
x = 11 % 2
x = 1
y = 6 % 2
y = 0
y != x
This would return false cause x and y are not equal. ( If you would run your code with the given example values )
To learn more about Modulus you can look here, or just on any other basic C++ Tutorial.
it returns true if remainder of the division for tail + 1 and head is the same
for example if tail is 2, head is 1 and N is 2
(tail + 1) % N is 1
head % N is 1 too
so whole expression returns true
string temp is equal to "ZERO:\t.WORD\t1" from my debugger. (the first line of my file)
string temp = RemoveWhiteSpace(data);
int i = 0;
if ( temp.length() > 0 && isalpha(temp[0]) )
cout << "without true worked" << endl;
if ( temp.length() > 0 && isalpha(temp[0]) == true )
cout << "with true worked" << endl;
This is my code to check if first character of temp is a a-z,A-Z. The first if statement will evaluate to true and the 2nd to false. WHY?!?!?! I have tried this even without the "temp.length() > 0 &&" and it still evaluates false. It just hates the "== true". The only thing I can think of is that isalpha() returns != 0 and true == 1. Then, you could get isalpha() == 2 != 1. But, I have no idea if C++ is that ... weird.
BTW, I dont need to know that the "== true" is logically pointless. I know.
output was
without true worked
Compiled with CodeBlock using GNU GCC on Ubuntu 9.10 (if this matters any)
The is* functions are only guaranteed to return a non-zero value if true, NOT necessarily a 1. A typical implementation is table based, with one entry in the table for each character value, and a set of bits defining which bit means what. The is* function will just AND the right bitmask with the table value, and return that, which will only be the value 1 for whichever type happens to have been given bit position 0.
E.g.:
#define __digit 1
#define __lower 2
#define __upper 4
extern int __type_table[];
int isdigit(int c) {
return __type_table[c+1] & __digit;
}
int isalpha(int c) {
return __type_table[c+1] & (__lower | __upper);
}
int islower(int c) {
return __type_table[c+1] & __lower;
}
int isupper(int c) {
return __type_table[c+1] & __upper;
}
Where __type_table is defined as something like int __type_table[UINT_MAX+1]; and would be initialized so (for example) __type_table['0'+1] == __digit and __type_table['A'+1] == __upper.
In case you care, the '+1' part is to leave a spot at the beginning of the table for EOF (which is typically defined as -1).
isalpha doesn't return true, it returns non-zero. This is quite common for API designed for C.
Note that in the expression isalpha(ch) == true, the subexpression true is promoted to type int with value 1.
Well, the documentation suggests that it returns either zero or non-zero, not necessarily just false or true. So you'd better check (isalpha(temp[0]) != 0).
Do not isalpha(ch) == true, but !!isalpha(ch) == true