Odd variable assignment [duplicate] - c++

This question already has answers here:
Uses of C comma operator [duplicate]
(20 answers)
Closed 9 years ago.
Good day, everyone.
I've come across a peculiar piece of code today, which I don't quite understand.
I don't even know how to search for this particular problem.
In this code, which works, a variable assignment is done like this:
if(condition) {
Var1 = false, Var2 = false;
}
Now, I was under the impression, that ALL commands need to be terminated by a semicolon instead of a comma. I am familiar with the syntax
Var1 = Var2 = false;
but not with the one posted above. The compiler (g++) doesn't even throw me a warning or anything...am I missing something from the specification here?
Or is the compiler generous with me and just replaces the , with a ; internally? If so, shouldn't he at least throw a warning?
Thank you for your time.

am I missing something from the specification here?
Yes, it's the "comma operator", specified by C++11 5.18. It evaluates the sub-expression to the left, then the one to the right, and the overall result is that of the right-hand one.
In this case, it's equivalent to two expression statements separated by ;
It's useful in places like if/while/for where you're only allowed one expression, but might want to do more than one thing:
while (++i, --j != 0)
and also if you like to jam multiple statements together to make life difficult for whoever has to read your code.

In the C and C++ programming languages, the comma operator (represented by the token ,) is a binary operator that evaluates its first operand and discards the result, and then evaluates the second operand and returns this value (and type). (read more)

As Alexandru Barbarosie pointed out, there's quite a thorough explanation on what's happening at https://stackoverflow.com/questions/1613230/uses-of-c-comma-operator
To quickly summarize it for whomever stumbles across this post: When used outside of for loops and stuff, the , actually has the same effect as the ;.
For more information, please visit the link.

Related

What does C++ if-Statement with double parantheses do?

I have stumbled upon an if statement where the condition is actually an assignment and I don't really understand what it does. Now, I found a similar Question with extensive answers but I still don't quite understand, what my snippet does:
if ((x = !x))
/* some code */
The similar question I found is this one: https://unix.stackexchange.com/questions/306111/what-is-the-difference-between-the-bash-operators-vs-vs-vs
One user states, that
((…)) double parentheses surround an arithmetic instruction, that is, a computation on integers, with a syntax resembling other programming languages. This syntax is mostly used for assignments and in conditionals. This only exists in ksh/bash/zsh, not in plain sh.
What does that mean? Is the value of x toggled now and nothing else happened? In what case does this condition return false?
It does the same thing as if(x = !x) does. However, because it is very easy to accidentally use = in place of ==, compilers will warn you when you're using an assignment inside of an if statement. That warning doesn't get displayed if the assignment expression is inside of a second set of parenthesis.
So that's the point of the extra parens: to tell the compiler/reader that the writer really meant to use assignment rather than equality testing.

Performance when using sequence of operations in a single line in cpp [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
Recently I have started looking into C++ from the basics and got to know (to my surprise) that I can give series of expressions in a single line separated by commas in some cases as below
//it'll execute all the expressions mentioned after condition seperated by comma
for(int i=0;condition;++i,++x,cout<<"in for loop"<<endl,z = z*2);
(x>y)? ++z,z1 = z*2, cout<<"printing statement"<<endl:cout<<"condition failed"<<endl,z = z/2;
Here, I have a confusion after this is working. Is it safe to code in that way or is there any problem coding in such a way?
Please clarify!!!
Correct me if i'm wrong anywhere, I'm just curious to know why most of the programmers don't use this way (I haven't seen such kind of lines anywhere)
The comma operator , evaluates each of its operands in sequence. In standardese, there is a sequence point between the evaluation of the left operand and the right operand.
In a expression which contains a comma operator, the value of the left operand is discarded and the expression takes on the value of the right operand. In both of the examples above, the comma operator is used in a void context, so none of the values are used.
So a statement like this where the value of the comma operator is not used:
exp1, exp2, exp3, exp4;
Is equivalent to the following sequence of statements:
exp1; exp2; exp3; exp4;
The first example is equivalent to the following:
for(int i=0;condition;) {
++i;
++x;
cout<<"in for loop"<<endl;
z = z*2;
}
And the second example:
if (x>y) {
++z;
z1 = z*2;
cout<<"printing statement"<<endl;
} else {
cout<<"condition failed"<<endl;
z = z/2;
}
Note that this is considerably more readable that the one-line versions. It's also easier to debug. Since debuggers typically step through code a line at a time, it breaks up the flow and is more granular.
Not indenting and spacing your code is not less costly regarding performance. It is unreadable, confusing and a pain to understand for you and for anyone who'd have to work with it.
Lot of people will prefer a well-syntaxed, beautifully and efficiently-indented code than a top-performance one. You can modify, debug and refract a code which might not work but has the advantage to be understandable.
On the other hand, very few codes remain unchanged and stay unread. There will always be a time when someone, may be you, will have to read it again and if it looks like the one if your OP, it will be very time costly to do.
It is allowed. In my opinion and i say without a reference that in general other programmers do not find your 'for' loop very readable. Sometimes in a for loop you want to do other things then just for (int i = 0; i < 10; ++i){"do something"}For example increment 'i' in every loop with two. Reading code should be like reading a text. If you are reading a book you do not want it to be unnecessary difficult.
Your other question was about the safety of the statement. The biggest problem with the code is that you might get confused about what you are doing exactly. Bugs are caused by human errors (computers are deterministic and are executing machine code which ultimately has been written by a human) and the question about safety mainly depends on how you define it.
To give you some tips. When i just started programming C++ i looked a lot on CPP reference. I will give you a link where you can read about the syntax and what is allowed/possible. On this website there are quite a lot of examples on all kinds of statements. They will in general not put 5 or 6 operations within in a single line. If there are more variables that you want to change then you might want to do that in the scope of the for loop so it will be more readable instead of inside the for loop.
http://en.cppreference.com/w/cpp/language/for

Double increment on an integer variable, does it work as intended? [duplicate]

This question already has answers here:
Multiple preincrement operations on a variable in C++(C ?)
(2 answers)
Closed 6 years ago.
I have some code with lines which increment a counter.
++ count;
Sometimes I have an if condition which means I should increment count by 2.
count += 2;
Does "double increment'ing" work in the same way?
++ ++ count;
It would be helpful to know if both C and C++ compilers interpret this the same way.
As this is clearly syntactically correct, the question that remains is: "Is this UB because of unsequenced writes?"
It is not (in C++11 and later) because
5) The side effect of the built-in pre-increment and pre-decrement operators is sequenced before its value computation (implicit rule due to definition as compound assignment)
(From here)
So the code is fine as of C++11.
However, the sequencing rules were different before that, and pre-C++11, the code actually has UB.
In C, that code does not even compile.
The fact that the behavior is different between C and C++ and even between different C++ standards and that this question arises in the first place is a hint that the simple count += 2; is the safer and more readable version. You should prefer it over the "cute and clever" ++ ++count;.
There are two methods. One that obviously works, one where you have to ask a question on StackOverflow. There are comments saying "in C++ 11 or later"... How sure are you that your C++ code runs with C++ 11 and not something older? Even if you use extensions that were not part of an earlier language, your language could be C++0x with some extensions.
Clearly you shouldn't care whether the second method works or not, but use the one that obviously works.

Read and write variable in an IF statement

I'm hoping to perform the following steps in a single IF statement to save on code writing:
If ret is TRUE, set ret to the result of function lookup(). If ret is now FALSE, print error message.
The code I've written to do this is as follows:
BOOLEAN ret = TRUE;
// ... functions assigning to `ret`
if ( ret && !(ret = lookup()) )
{
fprintf(stderr, "Error in lookup()\n");
}
I've got a feeling that this isn't as simple as it looks. Reading from, assigning to and reading again from the same variable in an IF statement. As far as I'm aware, the compiler will always split statements like this up into their constituent operations according to precedence and evaluates conjuncts one at a time, failing immediately when evaluating an operand to false rather than evaluating them all. If so, then I expect the code to follow the steps I wrote above.
I've used assignments in IF statements a lot and I know they work, but not with another read beforehand.
Is there any reason why this isn't good code? Personally, I think it's easy to read and the meaning is clear, I'm just concerned about the compiler maybe not producing the equivalent logic for whatever reason. Perhaps compiler vendor disparities, optimisations or platform dependencies could be an issue, though I doubt this.
...to save on code writing This is almost never a valid argument. Don't do this. Particularly, don't obfuscate your code into a buggy, unreadable mess to "save typing". That is very bad programming.
I've got a feeling that this isn't as simple as it looks. Reading from, assigning to and reading again from the same variable in an IF statement.
Correct. It has little to do with the if statement in itself though, and everything to do with the operators involved.
As far as I'm aware, the compiler will always split statements like this up into their constituent operations according to precedence and evaluates conjuncts one at a time
Well, yes... but there is operator precedence and there is order of evaluation of subexpressions, they are different things. To make things even more complicated, there are sequence points.
If you don't know the difference between operator precedence and order of evaluation, or if you don't know what sequence points are, you need to instantly stop stuffing as many operators as you can into a single line, because in that case, you are going to write horrible bugs all over the place.
In your specific case, you get away with the bad programming just because as a special case, there happens to be a sequence point between the left and right evaluation of the && operator. Had you written some similar mess with a different operator, for example ret + !(ret = lookup(), your code would have undefined behavior. A bug which will take hours, days or weeks to find. Well, at least you saved 10 seconds of typing!
Also, in both C and C++ use the standard bool type and not some home-brewed version.
You need to correct your code into something more readable and safe:
bool ret = true;
if(ret)
{
ret = lookup();
}
if(!ret)
{
fprintf(stderr, "Error in lookup()\n");
}
Is there any reason why this isn't good code?
Yes, there are a lot issues whith such dirty code fragments!
1)
Nobody can read it and it is not maintainable. A lot of coding guidlines contain a rule which tells you: "One statement per line".
2) If you combine multiple expressions in one if statement, only the first statements will be executed until the expression is defined! This means: if you have multiple expressions which combined with AND the first expression which generates false will be the last one which will be executed. Same with OR combinations: The first one which evaluates to true is the last one which is executed.You already wrote this and you! know this, but this is a bit of tricky programming. If all your colleges write code that way, it is maybe ok, but as I know, my colleagues will not understand what you are doing in the first step!
3) You should never compare and assign in one statement. It is simply ugly!
4) if YOU! already think about " I'm just concerned about the compiler maybe not producing the equivalent logic" you should think again why you are not sure what you are doing! I believe that everybody who must work with such a dirty code will think again on such combinations.
Hint: Don't do that! Never!

Meaning of a comma in a number [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
C++ Comma Operator
that probably a trivial question, but I don't know the answer. And this has been troubling me this afternoon.
I was just writing a function to convert RVB to YUV. Nothing really special, but mistakenly used the comma (,) instead of a dot in my numbers.
It compiles but the result was not what I expected, for example "-3713796" instead of a 0-255 range number.
(0,615*(double) 61) - (0,51498*(double) 61) - (0,10001*(double) 61)
So what does it mean ?
If it's not a compilation error, it's probably usefull for something but what?
Ps: I was using C++ with Qt.
You've accidentally used the comma operator. It evaluates its first operand and discards the result, and then evaluates the second operand and returns its value and type.
In my experience, it's most commonly used in loop statements. For other uses, see Uses of C comma operator
It's the comma operator which evaluates each operand and returns the rightmost. In this case it evaluated 0, then 615*(double) 61 and resulted in a value of that product.