a pair of number enclosed in parentheses - c++

Here is a block of code. Can anyone explain what it means to have a pair of numbers enclosed inside parentheses. (This is in C++.)
int a = 2, b = 2, c = 3, d = 1;
if((a,b)<(c,d))
cout<<"case1"<<endl;
else
cout<<"case2";

That's the comma operator; it evaluates the thing on the left, throws the result out, and returns the result on the right. Since evaluating an int variable has no side-effects, that if is semantically equivalent to
if(b < d)

Or if the value are changing or taken as an input by user you can use && (and), || (or) logical operators to sort out your codes
if ((a<c) && (b<d))
or
if ((a<c) || (b<d))
That way you can make cases the way you like. Check about operators here http://www.cplusplus.com/doc/tutorial/operators/

Related

C++ multiple operators: assign A or B not equal to C

I am currently learning from an SDL2/OpenGL2 example code, for ImGui. Then, I ran into a line (and a few more alike) as shown below. I believe this part binds SDL mouse events to IMGUI API. However, I do not quite understand how it works.
io.MouseDown[0] = g_MousePressed[0] || (mouseMask & SDL_BUTTON(SDL_BUTTON_LEFT)) != 0
where,
ImGuiIO& io = ImGui::GetIO();
bool mouseDown[5]; // a member of ImGuiIO struct
static bool g_MousePressed[3] = { false, false, false };
Uint32 mouseMask = SDL_GetMouseState(&mx, &my);
(I hope above is enough information...)
What makes me the most confused is the the last part, not equal to 0. I could understand it, if it was a simple assignment of the result of an And and an Or operations. However, there is not equal to zero following at the end and I have not seen this before. I would like to get some help to understand this code please.
expression != 0
is a boolean expression and thus evaluates to either true or false which can be converted to integer values of 0 or 1.
#include <iostream>
int main() {
constexpr size_t SDL_BUTTON = 5;
for (size_t mouseMask = 0; mouseMask < 16; ++mouseMask) {
std::cout << mouseMask << ' '
<< (mouseMask & SDL_BUTTON) << ' '
<< ((mouseMask & SDL_BUTTON) != 0) << '\n';
}
}
Live demo: http://ideone.com/jcmosg
Since || is the logical or operator, we are performing a logical comparison that tests whether io.MouseDown != 0 or (mouseMask & SDL_BUTTON(SDL_BUTTON_LEFT)) != 0 and yields a boolean value (true or false) promoted to whatever type io.mouseDown[0] is.
The code could actually have been written as:
io.MouseDown[0] = g_MousePressed[0] || (mouseMask & SDL_BUTTON(SDL_BUTTON_LEFT))
or
const bool wasPressed = g_mousePressed[0];
const bool newPress = mouseMask & SDL_BUTTON(SDL_BUTTON_LEFT);
const either = (wasPressed == true) || (newPress == true);
io.MouseDown[0] = either;
or
if (g_mousePressed[0])
io.MouseDown[0] = 1;
else if (mouseMask & SDL_BUTTON(SDL_BUTTON_LEFT))
io.MouseDown[0] = 1;
else
io.MouseDown[0] = 0;
See http://ideone.com/TAadn2
If you are intending to learn, find yourself a good sandbox (an empty project file or an online ide like ideone.com etc) and teach yourself to experiment with pieces of code you don't immediately understand.
An expression a = b || c!=0 means a = (b!=0) || (c!=0). In boolean logic, b and b!=0 are equivalent. That's what I think the most confusing part. Once this is understood, there should be no problem.
Note that this expression should not be confused with a=b|c!=0, where | is a binary operation called "bit-wise or", as opposed to the logical operation ||, which is the logical "or". When doing b|c!=0, c!=0 is calculated first to yield a logical value 0 or 1, then b|0 or b|1 is calculated to do nothing (first case) or reset the last bit of the binary code of b to 1 (second case). Finally, that result is assigned to a. In this case, b and b!=0 are not equivalent, because the bit-wise or | is used instead of the logical or ||.
Similarly, & is the "bit-wise and" operator, while && is the logical "and". These two should not be confused either.
Notice that != has a higher precedence than ||, so the whole expression is indeed a simple assignment of the result of an OR.
The !=0 part is a way to turn the result of applying a bitmask into bool, as #AlekDepler said. Funny thing is its pretty much redundant (if mouseMask is of built-in integral type) as implicit conversion from say int to bool works exactly like !=0.

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.

What is this syntax in while loop condition?

while ( (i=t-i%10 ? i/10 : !printf("%d\n",j)) || (i=++j<0?-j:j)<101 );
I came across this on codegolf
Please explain the usage of ? and : and why is there no statement following the while loop? As in why is there a ; after the parenthesis.
There is a boolean operation going on inside the parentheses of the while loop:
while (boolean);
Since the ternary operator is a boolean operator, it's perfectly legal.
So what's this doing? Looks like modular arithmetic, printing going on over a range up to 101.
I'll agree that it's cryptic and obscure. It looks more like a code obfuscation runner up. But it appears to be compilable and runnable. Did you try it? What did it do?
The ?: is a ternary operator.
An expression of form <A> ? <B> : <C> evaluates to:
If <A> is true, then it evaluates to <B>
If <A> is false, then it evaluates to <C>
The ; after the while loop indicates an empty instruction. It is equivalent to writing
while (<condition>) {}
The code you posted seems like being obfuscated.
Please explain the usage of ? and :
That's the conditional operator. a ? b : c evaluates a and converts it to a boolean value. Then it evaluates b if its true, or c if its false, and the overall value of the expression is the result of evaluating b or c.
So the first sub-expression:
assigns t-i%10 to i. The result of that expression is the new value of i.
if i is not zero, the result of the expression is i/10
otherwise, print j, and the result of the expression is zero (since printf returns a non-zero count of characters printed, which ! converts to zero).
Then the second sub-expression, after ||, is only evaluated if the result of the first expression was zero. I'll leave you to figure out what that does.
why is there no statement following the while loop?
There's an empty statement, ;, so the loop body does nothing. All the action happens in the side effects of the conditional expression. This is a common technique when the purpose of the code is to baffle the reader; but please don't do this sort of thing when writing code that anyone you care about might need to maintain.
This is the Conditional Operator (also called ternary operator).
It is a one-line syntax to do the same as if (?) condition doA else (:) doB;
In your example:
(i=t-i%10 ? i/10 : !printf("%d\n",j)
Is equivalent to
if (i=t-i%10)
i/10;
else
!printf("%d\n",j);
?: is the short hand notation for if then else
(i=t-i%10 ? i/10 : !printf("%d\n",j)<br>
equals to
if( i= t-i%10 )
then { i/10 }
else { !printf("%d\n",j) }
Your while loop will run when the statement before the || is true OR the statement after the || is true.
notice that your code does not make any sense.
while ( (i=t-i%10 ? i/10 : !printf("%d\n",j)) || (i=++j<0?-j:j)<101 );
in the most human-readable i can do it for u, it's equivalent to:
while (i < 101)
{
i = (t - i) % 10;
if (i > 0)
{
i = i / 10;
}
else
{
printf("%d\n",j);
}
i = ++j;
if (i < 0)
{
i = i - j;
}
else
{
i = j;
}
}
Greetings.
I am the proud perpetrator of that code. Here goes the full version:
main()
{
int t=getchar()-48,i=100,j=-i;
while ((i=t-i%10?i/10:!printf("%d\n",j)) || (i=++j<0?-j:j)<101 );
}
It is my submission to a programming challenge or "code golf" where you are asked to create the tinniest program that would accept a digit as a parameter and print all the numbers in the range -100 to 100 that include the given digit. Using strings or regular expressions is forbidden.
Here's the link to the challenge.
The point is that it is doing all the work into a single statement that evaluates to a boolean. In fact, this is the result of merging two different while loops into a single one. It is equivalent to the following code:
main()
{
int i,t=getchar()-'0',j=-100;
do
{
i = j<0? -j : j;
do
{
if (t == i%10)
{
printf("%d\n",j);
break;
}
}
while(i/=10);
}
while (j++<100);
}
Now lets dissect that loop a little.
First, the initialisation.
int t=getchar()-48,i=100,j=-i;
A character will be read from the standard input. You are supposed to type a number between 0 and 9. 48 is the value for the zero character ('0'), so t will end up holding an integer between 0 and 9.
i and j will be 100 and -100. j will be run from -100 to 100 (inclusive) and i will always hold the absolute value of j.
Now the loop:
while ((i=t-i%10?i/10:!printf("%d\n",j)) || (i=++j<0?-j:j)<101 );
Let's read it as
while ( A || B ) /* do nothing */ ;
with A equals to (i=t-i%10?i/10:!printf("%d\n",j)) and B equals to (i=++j<0?-j:j)<101
The point is that A is evaluated as a boolean. If true, B won't be evaluated at all and the loop will execute again. If false, B will be evaluated and in turn, if B is true we'll repeat again and once B is false, the loop will be exited.
So A is the inner loop and B the outer loop. Let's dissect them
(i=t-i%10?i/10:!printf("%d\n",j))
It's a ternary operator in the form i = CONDITION? X : Y; It means that first CONDITION will be evaluated. If true, i will be set to the value of X; otherwise i will be set to Y.
Here CONDITION (t-i%10) can be read as t - (i%10). This will evaluate to true if i modulo 10 is different than t, and false if i%10 and t are the same value.
If different, it's equivalent to i = i / 10;
If same, the operation will be i = !printf("%d\n",j)
If you think about it hard enough, you'll see that it's just a loop that checks if any of the decimal digits in the integer in i is equal to t.
The loop will keep going until exhausting all digits of i (i/10 will be zero) or the printf statement is run. Printf returns the number of digits printed, which should always be more than zero, so !printf(...) shall always evaluate to false, also terminating the loop.
Now for the B part (outer loop), it will just increment j until it reaches 101, and set i to the absolute value of j in the way.
Hope I made any sense.
Yes, I found this thread by searching for my code in google because I couldn't find the challenge post.

Odd if statements

I didn't think these if's would compile but they do:
if (a>>b&&c&&d)
if (month==1,2,3,5,7,9,10)
The first I'm clueless about. In the second statement is the comma supposed to be an (||) or operator ?
Syntax wise was it always this way or was it introduced some time ago ?
I'm using Visual Studio 2010.
if (a>>b && c && d)
it is equal to
if ((a>>b) && c && d)
if the result of a shifted right b times evaluates to a bool, c and d also evaluates to bool respectively, then all these booleans will be AND-ed to each other.
In your context, the all expressions within commas will be evaluated and then the last expression will be passed to if expression:
if (month==1,2,3,5,7,9,10) -> is equal to
if (2,3,5,7,9,10) -> is equal to
if (3,5,7,9,10) -> is equal to
if (5,7,9,10) -> is equal to
if (7,9,10) -> is equal to
if (9,10) -> is equal to
if (10)
which is always true.
It's not suppose to be || or &&. If you want OR or AND write it like below:
if (month==1 || month==2 || month==3 || ....)
or
if (month==1 && month==2 && month==3 && ....)
// Also month can not simultaneously be equal to more than one value!
// then, it's equal to
if (false)
The first if statement would be evaluated like:
if(((a >> b) && c) && d)
Essentially bitshift a by b bits and then logical and with c and then with d
The second is the comma operator which will evaluate the first term and throw it away, then the second, and so on and return the result of the final term. So in our case the statement is equivalent to:
if(10)
which is always true.

Effect of using a comma instead of a semi-colon in C and C++

I've noticed on a number of occasions when refactoring various pieces of C and C++ code that a comma is used rather than a semi-colon to seperate statements. Something like this;
int a = 0, b = 0;
a = 5, b = 5;
Where I would have expected
int a = 0, b = 0;
a = 5; b = 5;
I know that C and C++ allow use of commas to seperate statements (notably loop headers), but what is the difference if any between these two pieces of code? My guess is that the comma has been left in as the result of cut & pasting, but is it a bug and does it effect execution?
It doesn't make a difference in the code you posted. In general, the comma separates expressions just like a semicolon, however, if you take the whole as an expression, then the comma operator means that the expression evaluates to the last argument.
Here's an example:
b = (3, 5);
Will evaluate 3, then 5 and assign the latter to b. So b = 5. Note that the brackets are important here:
b = 3, 5;
Will evaluate b = 3, then 5 and the result of the whole expression is 5, nevertheless b == 3.
The comma operator is especially helpful in for-loops when your iterator code is not a simple i++, but you need to do multiple commands. In that case a semicolon doesn't work well with the for-loop syntax.
The comma is a operator that returns a value which is always the 2nd (right) argument while a semicolon just ends statements. That allows the comma operator to be used inside other statements or to concatenate multiple statements to appear as one.
Here the function f(x) gets called and then x > y is evaluated for the if statement.
if( y = f(x), x > y )
An example when it's used just to avoid a the need for block
if( ... )
x = 2, y = 3;
if( ... ) {
x = 2;
y = 3;
}
The comma operator evaluates all operands from left to right, and the result is the value of the last operand.
It is mostly useful in for-loops if you want to do multiple actions in the "increment" part, e.g (reversing a string)
for (int lower = 0, upper = s.size() - 1; lower < upper; ++lower, --upper)
std::swap(s[lower], s[upper]);
Another example, where it might be an option (finding all occurrences in a string):
#include <string>
#include <iostream>
int main()
{
std::string s("abracadabra");
size_t search_position = 0;
size_t position = 0;
while (position = s.find('a', search_position), position != std::string::npos) {
std::cout << position << '\n';
search_position = position + 1;
}
}
In particular, logical and cannot be used for this condition, since both zero and non-zero can mean that the character was found in the string. With comma, on the other hand, position = s.find() is called each time when the condition is evaluated, but the result of this part of the condition is just ignored.
Naturally there are other ways to write the loop:
while ((position = s.find('a', search_position)) != std::string::npos)
or just
while (true) {
position = s.find('a', search_position);
if (position == std::string::npos)
break;
...
}
As Frank mentioned, how the comma operator is used in your example doesn't cause a bug. The comma operator can be confusing for several reasons:
it's not seen too often because it's only necessary in some special situations
there are several other syntactic uses of the comma that may look like a comma operator - but they aren't (the commas used to separate function parameters/arguments, the commas used to separate variable declarations or initializers)
Since it's confusing and often unnecessary, the comma operator should be avoided except for some very specific situations:
it can be useful to perform multiple operation in one or more of a for statement's controlling expressions
it can be used in preprocessor macros to evaluate more than one expression in a single statement. This is usually done to allow a macros to do more than one thing and still be a a single expression so the macro will 'fit' in places that only allow an expression.
The comma operator is a hackish operator pretty much by definition - it's to hack in 2 things where only one is allowed. It's almost always ugly, but sometimes that's all you've got. And that's the only time you should use it - if you have another option, don't use the comma operator.
Off the top of my head I can't think of too many other reasons to use the operator, since you can get a similar effect by evaluating the expressions in separate statements in most other situations (though I'm sure that someone will comment on a another use that I've overlooked).
One usage would be in code golfing:
if (x == 1) y = 2, z = 3;
if (x == 1) { y = 2; z = 3; }
The first line is shorter, but that looks too confusing to use in regular development.