+ 1
Operator precedence
Can some one explain the following code ? #include<iostream> using namespace std; int main(){ int a = 5; cout<<a&&0; return 0; } #include<iostream> using namespace std; int main(){ int a = 5; char b = âAâ; cout<<a|b; return 0; } #include<iostream> using namespace std; int main(){ int a = 3; cout<<(a>>1)%3; return 0; }
4 Answers
+ 2
Super
I made the following program for you. And I hope that all your questions have an answer in there.
If you declare a new variable that have the AND or OR operation, the resulted is the expected one:
int a = 5;
int b = a && 0;
If you use AND or OR in a cout, the result is not always the expected one:
cout << a && 0 gives 5 instead of 0, the correct one. Or cout << (a && 0) give 0 which is correct. While cout << "(5&&0)" is a simple string (5&&0) will be as output.
https://code.sololearn.com/cQK6XGZu8H4F/?ref=app
+ 2
(continue to the previous message) if you do OR operation on those 2 binary values:
0000 0101 OR
0100 0001
-â---------------
0100 0101
So, if my calculations are right it should print 'A'.
Finally, in the 3rd program you have (a>>1)%3. The >> operator is also from bitwise operator category, specifically the bitwise right shift operator. It can be translated as dividing by 2 as many times specified, in your case one time devided by 2. So, 3 / 2 is 1 (as a integer). Then 1 % 3 is the Modulus operator or the Remainder or Perfect Divisibility operator. 1%3 has the reminder 1. So, 1 will be printed.
Bonus: cout <<, where << is not a bitwise operator. It is called the insert operator. In case of cin >>, >> is called the extracting operator.
In conclusion, I recommend you to take the C course first and the C++ after.
+ 1
You have not one code, but 3 programs in C++. Each programs starts with the pre-processor directive #include.
The pre-processor directive #include is used in the first stage of program executing, when the pre-processor adds to your program all the source code present in the iostream.hpp (which is a library).
Next, std is a namespace that contain all the C++ functionality under a single scope.
main() is the entry point of every C++ program. It has no input parameters and returns an integer.
a is an integer variable initialized with 5.
cout is the printing function or displaying on std.
a&&0 is a Logical operation, where && is logical AND, it means 5 AND 0 or can be translated to TRUE AND FALSE. It will print 0.
In the 2nd program you have a|b or 5 OR 'A', where | is a bitwise operator, bitwise OR. I'm not sure what will print, and I don't want to test your program. You can do it yourself. I guess it will print a number in binary form (5 is 0000 0101 and 'A' in ASCII is 65 which is in binary 0100 0001
0
Thanks for the reply Romeo Cojocaru
I have a follow up question , if you dont mind
What causes different result when you are using a â(5&&0)â and cout <<5&&0
The first one hase a vlaue of 0 , but the second one has a value of 5
Can you explain the difference