I have some code in an old desktop app, which I inheritted from a colegue who left the company.
Here is a short similar example of the actual code I have:
#include <iostream>
int getType(int type)
{
return type;
}
int main()
{
int variable1 = 30;
int variable2 = 40;
int result = (getType(30) == (variable1 || variable2) ? 1 : 2);
std::cout << result << std::endl;
}
For the result I always receive 2, not 1 as I expected.
If I try:
int result = (getType(30) == (variable1) ? 1 : 2)
the result is true.
I can't figure out why this part:
int result = (getType(30) == (variable1 || variable2) ? 1 : 2)
is not true...
In the initializer expression of this declaration
int result = (getType(30) == (variable1 || variable2) ? 1 : 2);
the subexpression (variable1 || variable2) has the type bool and its value is true (variable1 isn't 0 so that is true) that is implicitly converted to the integer value 1 in the expression with the equality operator (getType(30) == (variable1 || variable2) .
From the C++17 Standard (7.6 Integral promotions)
6 A prvalue of type bool can be converted to a prvalue of type int,
with false becoming zero and true becoming one.
So as getType(30) is not equal to 1 the result of the initializer expression is 2.
To get the expected result you should rewrite the declaration like
int result = (getType(30) == variable1 || getType(30) == variable2) ? 1 : 2;
I think perhaps your understanding of the || operator is not quite right. The || operator is the or operator, and it will return a boolean result, false or true. In your code, you are doing this comparison: getType(30) == (variable1 || variable2). The parenthesis get evaluated first because of order of operations and you end up with getType(30) == true, since variable1 has a non-zero value. getType(30) evaluates and returns 30, so the expression is 30 == true. The true value then gets coerced to a 1 because of the rules of c++ and we evalate 30 == 1 which is false.
I think what you are asking for is why this doesn't do what you expect. And I see two problems, the one is that the getType function doesn't actually do what you might expect, it simply returns the variable. I'm not sure what you would expect in c++, but that's definitely a problem. The other expectation is probably that you want to compare the return of getType(30) with both variable1 and variable2 which would require a longer expression. The expression you want is probably getType(30) == variable1 || getType(30) == variable2. This is a common problem because in english we say 'if gettype equals var1 or var2`, but it doesn't translate into code like that unfortunately.
My code looks like this:
/*
* A B
* 0 0 -> 1
* 0 1 -> 0
* 1 0 -> 0
* 1 1 -> 0
*/
#define A condition_1
#define B condition_2
if (A) {
// do nothing
} else {
if (B) {
// do nothing
} else {
// do something
}
}
Above I've reported the truth table for two conditions where 1 is true and 0 is false, is there a way to express the truth table into a single if-condition?
Your truth table represents a NOR (not or) operation. You can get that easily by combining logical NOT (!) with logical OR (||)
if (!(A || B)) {
}
PS. Please, don't use #define macros. It's very error-prone and tends to bite programmers who use it. Most often there are safer and more readable ways to perform what macro does.
Use:
if (!A && !B) {
// do something
}
Think, your truth table only returns 1 when both conditions are false (0 0 -> 1).
You can use ! in both to invert it.
If there is only one 1 in the table then it's essentially AND operation. If there is only one 0 then it's OR operation. If there are two of both then you can make it an equality operation.
When you know which operation to chose your next step is to figure out which operands should be negated. For AND both operands must turn to 1 to produce 1 (1 AND 1 = 1), so negate those who would otherwise produce 0. For OR it's opposite, negate those who would produce 1 when trying to have 0 a s result (0 OR 0 = 0)
For equality operation bear in mind that bool can either be true or false, so there are only two values. If you try to use something that is not a bool for a logical operand then there would be problems. With that in mind when you want to produce equality negate any of the operands if originally they don't produce correct result (0 == 0 = 1 and also 1 == 1 = 1, if you understand me).
In your particular case we have only one 1 in the table so it's an AND operation. Both operands are 0 for this 1 outcome so we have to negate both of them:
!A && !B
So I have this function that takes in an integer. But It doesn't work and I suspect that the if statement is not valid, I could not find anything on google regarding the issue, maybe my googling skills just suck.
if mynumber != (0 or 1 or 2 or 3 or 4 or 5 or 6 or 7 or 8) then
print("Please choose an integer number between 1-8")
end
Thanks for any help!!
Correct. That is not how you test things like that. You cannot test multiple values that way.
or requires expressions on either side and evaluates to a single expression. So (0 or 1 or 2 or 3 or 4 or 5 or 6 or 7 or 8) evaluates to 0 and your final expression is just if mynumber != 0 then.
To test multiple values like that you need to use or around multiple comparison expressions.
if (mynumber ~= 0) or (mynumber ~= 1) or (mynumber ~= 2) ... then (also notice ~= is the not-equal operator not !=).
Also be sure to note YuHao's answer about the logic in this line and how to test for this correctly.
Others have pointed the major problems you have, i.e, 0 or 1 or 2 or 3 or 4 or 5 or 6 or 7 or 8 evaluates as 0, the rest is ignored because of short-circuit. You need to test the number with these numbers one by one.
However, there's one last trap. The condition
if mynumber ~= 0 or mynumber ~= 1 then
is always true, because a number is either not equal to 0, in which case mynumber ~= 0 is true; or it is equal to 0, in which case mynumber ~= 1 is true.
The correct logic should be:
if mynumber ~= 0 and mynumber ~= 1 then
Etan's answer explains the behaviour as observed in lua. I'd suggest writing a custom FindIn function for searching:
function FindIn( tInput, Value )
for _ in pairs( tInput ) do
if Value == tInput[_] then return true end
end
return false
end
if FindIn( {1,2,3,4,5,6,7,8}, mynumber ) then
-- ...
end
try this:
In Lua You check if two items are NOT EQUAL by "~=" instead of "!=",
If You compare two items in if statement, then always remember that items should return booleans, so: instead of mynumber != (0 or 1 or...) try something like (mynumber ~= 0) or (mynumber ~= 1) ...
You can do it simple with .... (mynumber have to be integer variable)
if mynumber<0 or mynumber>8 then
print("Please choose an integer number between 1-8")
end
this is a small code that compares the 3 variables at a go . I have compared 2 codes.
FIRST
#include <iostream>
int main() {
if( 8 > 7 > 6) std::cout << "true";
else std::cout << "false";
std::cout << "\n";
std::cout << (8 < 9);
std::cout << "\n";
system("pause");
}
// output :
/* false
* 1
*/
SECOND
#include <iostream>
int main() {
if( 8 > (7 > 6) ) std::cout << "true"; // with brackets
else std::cout << "false";
std::cout << "\n";
std::cout << (8 < 9);
std::cout << "\n";
system("pause");
}
// output :
// true
// 1
I understand the second output but can't understand how is the ifstatement in the first code is evaluated ?
Please explain.
The relational operators are left-to-right, so 8>7>6 gets evaluated as (8>7)>6. 8>7 evaluates to true, which is converted to 1, so you get 1>6, which is false.
The C++ standard actually mentions this point explicitely:
The relational operators group left-to-right. [Example: a<b<c means (a<b)<c and not (a<b)&&(b<c). ]
if( 8 > 7 > 6) means if( (8 > 7) > 6) which means if( (1) > 6) which means if(false). That means, if block cannot execute, else block will be executed which prints false.
if( 8 > (7 > 6)) means if( ( 8 > (1) ) which means if(true). So if block gets executed which prints true.
And the value of (8<9) is easy to know if you know what < means. Well, (8<9) returns true which means 1.
The first code's if statement is evaluated in left-to-right order. ie: (8 > 7) > 6 which is evaluated as follows:
(8 > 7) > 6
(1) > 6
0
Note that (8 > 7) is true, so it returns the numerical equivalent for true, 1.
The overall evaluation comes to 0, ie. false.
An if statement is classically made to compare 2 statements, if you are wanting to compare more than 2 statements you should be using a boolean OR || or a boolean AND &&. The reasoning behind this is based in boolean logic. The statement that you posted in the first program evaluates from left to right meaning
if (8 >7)>6
If 8 is greater than 7 (which it is) it will evaluate to true, which is "1" in boolean logic (1 being true, 0 being false).
Thus after that evaluates you have:
if (1 > 6)
which naturally evaluates to false. Because the comparison is no longer 8/7/6, it's true / 6. And in this case, true is less than 6, thus a false.
If you were to set it up like this, would would have the expected results:
if (8 > 7 && 7 > 6)//Do stuff
or alternatively, if you wanted to be exhaustive..
if (8 > 7 && 7 > 6 && 8 > 6)
so all numbers are compared (this would be more sensible in the event that you had 3 variables, perhaps where x should be equal to 100, y should be equal to 50, and z should be equal to 25.)
You'd then have the comparison
if (x > y && y > z && x > y) //do stuff
This would evaluate to true in the event that your variables had the contents that you expected.
if(8 > 7 > 6) is evaluated like :
if((8 > 7) > 6)
if(true > 6)
true is implicitly casted to 1.
1 > 6 is false.
The if statement is evaluated left to right so it is the same as (8>7)>6.
8>7 is true which is equal to 1 so then it evaluates 1>6 which is false.
The relational operators associate from left to right!
8>7>6 = (8>7)>6 = 1>6 = FALSE
The associativity of operator ">" is from left to right, so it means that in your first example, "8 > 7" is evaluated first, and the result of that is 1, which is then evaluated against 6, which result is false.
In the second example, since you use brackets, the we have 8 > 1, which is true.
Hope this helps.
After reading Hidden Features and Dark Corners of C++/STL on comp.lang.c++.moderated, I was completely surprised that the following snippet compiled and worked in both Visual Studio 2008 and G++ 4.4.
Here's the code:
#include <stdio.h>
int main()
{
int x = 10;
while (x --> 0) // x goes to 0
{
printf("%d ", x);
}
}
Output:
9 8 7 6 5 4 3 2 1 0
I'd assume this is C, since it works in GCC as well. Where is this defined in the standard, and where has it come from?
--> is not an operator. It is in fact two separate operators, -- and >.
The conditional's code decrements x, while returning x's original (not decremented) value, and then compares the original value with 0 using the > operator.
To better understand, the statement could be written as follows:
while( (x--) > 0 )
Or for something completely different... x slides to 0.
while (x --\
\
\
\
> 0)
printf("%d ", x);
Not so mathematical, but... every picture paints a thousand words...
That's a very complicated operator, so even ISO/IEC JTC1 (Joint Technical Committee 1) placed its description in two different parts of the C++ Standard.
Joking aside, they are two different operators: -- and > described respectively in §5.2.6/2 and §5.9 of the C++03 Standard.
x can go to zero even faster in the opposite direction in C++:
int x = 10;
while( 0 <---- x )
{
printf("%d ", x);
}
8 6 4 2
You can control speed with an arrow!
int x = 100;
while( 0 <-------------------- x )
{
printf("%d ", x);
}
90 80 70 60 50 40 30 20 10
;)
It's equivalent to
while (x-- > 0)
x-- (post decrement) is equivalent to x = x-1 (but returning the original value of x), so the code transforms to:
while(x > 0) {
x = x-1;
// logic
}
x--; // The post decrement done when x <= 0
It's
#include <stdio.h>
int main(void) {
int x = 10;
while (x-- > 0) { // x goes to 0
printf("%d ", x);
}
return 0;
}
Just the space makes the things look funny, -- decrements and > compares.
The usage of --> has historical relevance. Decrementing was (and still is in some cases), faster than incrementing on the x86 architecture. Using --> suggests that x is going to 0, and appeals to those with mathematical backgrounds.
Utterly geek, but I will be using this:
#define as ;while
int main(int argc, char* argv[])
{
int n = atoi(argv[1]);
do printf("n is %d\n", n) as ( n --> 0);
return 0;
}
while( x-- > 0 )
is how that's parsed.
One book I read (I don't remember correctly which book) stated: Compilers try to parse expressions to the biggest token by using the left right rule.
In this case, the expression:
x-->0
Parses to biggest tokens:
token 1: x
token 2: --
token 3: >
token 4: 0
conclude: x-- > 0
The same rule applies to this expression:
a-----b
After parse:
token 1: a
token 2: --
token 3: --
token 4: -
token 5: b
conclude: (a--)-- - b
This is exactly the same as
while (x--)
Anyway, we have a "goes to" operator now. "-->" is easy to be remembered as a direction, and "while x goes to zero" is meaning-straight.
Furthermore, it is a little more efficient than "for (x = 10; x > 0; x --)" on some platforms.
This code first compares x and 0 and then decrements x. (Also said in the first answer: You're post-decrementing x and then comparing x and 0 with the > operator.) See the output of this code:
9 8 7 6 5 4 3 2 1 0
We now first compare and then decrement by seeing 0 in the output.
If we want to first decrement and then compare, use this code:
#include <stdio.h>
int main(void)
{
int x = 10;
while( --x> 0 ) // x goes to 0
{
printf("%d ", x);
}
return 0;
}
That output is:
9 8 7 6 5 4 3 2 1
My compiler will print out 9876543210 when I run this code.
#include <iostream>
int main()
{
int x = 10;
while( x --> 0 ) // x goes to 0
{
std::cout << x;
}
}
As expected. The while( x-- > 0 ) actually means while( x > 0). The x-- post decrements x.
while( x > 0 )
{
x--;
std::cout << x;
}
is a different way of writing the same thing.
It is nice that the original looks like "while x goes to 0" though.
There is a space missing between -- and >. x is post decremented, that is, decremented after checking the condition x>0 ?.
-- is the decrement operator and > is the greater-than operator.
The two operators are applied as a single one like -->.
It's a combination of two operators. First -- is for decrementing the value, and > is for checking whether the value is greater than the right-hand operand.
#include<stdio.h>
int main()
{
int x = 10;
while (x-- > 0)
printf("%d ",x);
return 0;
}
The output will be:
9 8 7 6 5 4 3 2 1 0
C and C++ obey the "maximal munch" rule. The same way a---b is translated to (a--) - b, in your case x-->0 translates to (x--)>0.
What the rule says essentially is that going left to right, expressions are formed by taking the maximum of characters which will form a valid token.
Actually, x is post-decrementing and with that condition is being checked. It's not -->, it's (x--) > 0
Note: value of x is changed after the condition is checked, because it post-decrementing. Some similar cases can also occur, for example:
--> x-->0
++> x++>0
-->= x-->=0
++>= x++>=0
char sep = '\n' /1\
; int i = 68 /1 \
; while (i --- 1\
\
/1/1/1 /1\
/1\
/1\
/1\
/1\
/ 1\
/ 1 \
/ 1 \
/ 1 \
/1 /1 \
/1 /1 \
/1 /1 /1/1> 0) std::cout \
<<i<< sep;
For larger numbers, C++20 introduces some more advanced looping features.
First to catch i we can build an inverse loop-de-loop and deflect it onto the std::ostream. However, the speed of i is implementation-defined, so we can use the new C++20 speed operator <<i<< to speed it up. We must also catch it by building wall, if we don't, i leaves the scope and de referencing it causes undefined behavior. To specify the separator, we can use:
std::cout \
sep
and there we have a for loop from 67 to 1.
Instead of regular arrow operator (-->) you can use armor-piercing arrow operator: --x> (note those sharp barbs on the arrow tip). It adds +1 to armor piercing, so it finishes the loop 1 iteration faster than regular arrow operator. Try it yourself:
int x = 10;
while( --x> 0 )
printf("%d ", x);
Why all the complication?
The simple answer to the original question is just:
#include <stdio.h>
int main()
{
int x = 10;
while (x > 0)
{
printf("%d ", x);
x = x-1;
}
}
It does the same thing. I am not saying you should do it like this, but it does the same thing and would have answered the question in one post.
The x-- is just shorthand for the above, and > is just a normal greater-than operator. No big mystery!
There are too many people making simple things complicated nowadays ;)
Conventional way we define condition in while loop parenthesis"()" and terminating condition inside the braces"{}", but this -- & > is a way one defines all at once.
For example:
int abc(){
int a = 5
while((a--) > 0){ // Decrement and comparison both at once
// Code
}
}
It says, decrement a and run the loop till the time a is greater than 0
Other way it should have been like:
int abc() {
int a = 5;
while(a > 0) {
a = a -1 // Decrement inside loop
// Code
}
}
Both ways, we do the same thing and achieve the same goals.
(x --> 0) means (x-- > 0).
You can use (x -->)
Output: 9 8 7 6 5 4 3 2 1 0
You can use (-- x > 0) It's mean (--x > 0)
Output: 9 8 7 6 5 4 3 2 1
You can use
(--\
\
x > 0)
Output: 9 8 7 6 5 4 3 2 1
You can use
(\
\
x --> 0)
Output: 9 8 7 6 5 4 3 2 1 0
You can use
(\
\
x --> 0
\
\
)
Output: 9 8 7 6 5 4 3 2 1 0
You can use also
(
x
-->
0
)
Output: 9 8 7 6 5 4 3 2 1 0
Likewise, you can try lot of methods to execute this command successfully.
This --> is not an operator at all. We have an operator like ->, but not like -->. It is just a wrong interpretation of while(x-- >0) which simply means x has the post decrement operator and this loop will run till it is greater than zero.
Another simple way of writing this code would be while(x--). The while loop will stop whenever it gets a false condition and here there is only one case, i.e., 0. So it will stop when the x value is decremented to zero.
Here -- is the unary post decrement operator.
while (x-- > 0) // x goes to 0
{
printf("%d ", x);
}
In the beginning, the condition will evaluate as
(x > 0) // 10 > 0
Now because the condition is true, it will go into the loop with a decremented value
x-- // x = 9
That's why the first printed value is 9
And so on. In the last loop x=1, so the condition is true. As per the unary operator, the value changed to x = 0 at the time of print.
Now, x = 0, which evaluates the condition (x > 0 ) as false and the while loop exits.
--> is not an operator, it is the juxtaposition of -- (post-decrement) and > (greater than comparison).
The loop will look more familiar as:
#include <stdio.h>
int main() {
int x = 10;
while (x-- > 0) { // x goes to 0
printf("%d ", x);
}
}
This loop is a classic idiom to enumerate values between 10 (the excluded upper bound) and 0 the included lower bound, useful to iterate over the elements of an array from the last to the first.
The initial value 10 is the total number of iterations (for example the length of the array), and one plus the first value used inside the loop. The 0 is the last value of x inside the loop, hence the comment x goes to 0.
Note that the value of x after the loop completes is -1.
Note also that this loop will operate the same way if x has an unsigned type such as size_t, which is a strong advantage over the naive alternative for (i = length-1; i >= 0; i--).
For this reason, I am actually a fan of this surprising syntax: while (x --> 0). I find this idiom eye-catching and elegant, just like for (;;) vs: while (1) (which looks confusingly similar to while (l)). It also works in other languages whose syntax is inspired by C: C++, Objective-C, java, javascript, C# to name a few.
That's what you mean.
while((x--) > 0)
We heard in childhood,
Stop don't, Let Go (روکو مت، جانے دو)
Where a Comma makes confusion
Stop, don't let go. (روکو، مت جانے دو)
Same Happens in Programming now, a SPACE makes confusion. :D
The operator you use is called "decrement-and-then-test". It is defined in the C99 standard, which is the latest version of the C programming language standard. The C99 standard added a number of new operators, including the "decrement-and-then-test" operator, to the C language. Many C++ compilers have adopted these new operators as extensions to the C++ language.
Here is how the code without using the "decrement-and-then-test" operator:
#include <stdio.h>
int main()
{
int x = 10;
while (x > 0)
{
printf("%d ", x);
x--;
}
}
In this version of the code, the while loop uses the > operator to test whether x is greater than 0. The x-- statement is used to decrement x by 1 at the end of each iteration of the loop.