about cout cin 2 var | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

about cout cin 2 var

if i type int a,b; cin >> a,b; cout << “a and b = ”<<a <<“and”<<b; if i input a=1 b=2 why output are 1 and 0?

5th Sep 2019, 10:52 AM
汝風留名
汝風留名 - avatar
7 Answers
+ 3
To get more than one variable using cin, it should look like cin >> a >> b; In your case, b is not being initialized, hence it still has some garbage value, in this case 0.
5th Sep 2019, 11:14 AM
Shadow
Shadow - avatar
+ 3
Ipang, do not take me for granted here, but I think that since the comma operator always has the lowest precedence, first cin >> a is called, afterwards the result is evaluated and discarded by the comma operator, and then b is evaluated and returned. Try running the following code snippet: int a { 1 }, b { 2 }; auto c = ( cin >> a, b ); cout << a << endl << b << endl << c << endl; Here c will equal b, because ultimately, b will be returned from the expression. Note the neccessary braces, without them the assignment is done before the comma operator is evaluated, resulting in c being assigned the result from cin >> a and therefore resulting in a compilation error.
5th Sep 2019, 9:17 PM
Shadow
Shadow - avatar
+ 3
Ipang, sorry for the misunderstanding, "do not take me for granted" <=> "do not assume me to be 100% correct on this, better do own research additionally". The correct term should have been "do not take this at face value". I wouldn't ever be annoyed by a ping of yours. :) Anyway, a compilation of pages that might be helpful, although you probably know most of them already: https://en.cppreference.com/w/cpp/language/operator_other https://www.fluentcpp.com/2018/07/31/how-to-get-along-with-the-comma-operator/ https://stackoverflow.com/questions/54142/how-does-the-comma-operator-work https://www.geeksforgeeks.org/comna-in-c-and-c/ https://codassium.com/blog/the-forgotten-comma-operator/
6th Sep 2019, 7:12 AM
Shadow
Shadow - avatar
+ 2
Shadow I was wondering how comma operator behaviour in that case, still not so clear about comma operator behaviour in different occasions. Need a little help here 😁
5th Sep 2019, 12:38 PM
Ipang
+ 1
Shadow First, I do not take you for granted - I hope my ping didn't bother you in any way. Thanks for replying, I asked because I found a lot of codes in Playground written to cover the wonder of this operator, and to see those codes kinda made me feel unsure about how the operator behaves, because what I predict doesn't match the code output sometimes (read: my prediction of code output be wrong). I'll see to it that I can solve this soon ✌
5th Sep 2019, 10:45 PM
Ipang
+ 1
No problem at all 😁 And Big Thanks for the references Shadow, I'll get to them soon. This really helps Thanks again 👍
6th Sep 2019, 9:11 AM
Ipang
0
oh i c thx~
5th Sep 2019, 11:17 AM
汝風留名
汝風留名 - avatar