I know the names of most of the operators but not sure what operator<< and operator>> are called.
i.e.
operator=() // the assignment operator
operator==() // the equality of comparison operator
operator++() // the increment operator
operator--() // decrement operator etc.
operator<() // the less-than operator
and so forth...
<< is both the insertion operator and the left-shift operator.
>> is the extraction operator and the right-shift operator.
In the context of iostreams, they are considered to be stream insertion/extraction. In the context of bit-shifting, they are left-shift and right-shift.
In C++ Streams,
<< is insertion operator.
>> is extraction operator.
In Binary Operations,
Right shift (>>)
Left shift (<<)
<< left shift
>> right shift
<< = Bitwise left shift
>> = Bitwise right shift
Bit Shift Operators
The original names were left shift operator (<<) and right shift operator (>>), but with their meanings perverted by streams into insertion and extraction, you could argue that even in bitwise operations << inserts bits on the right while >> extracts them. Consequently, I almost always refer to them as the insertion and extraction operators.
<< is the 'left-shift' operator. It shifts its first operand left by the number of bits specified by its second operand.
They are called the Guillemet Left and Guillemet Right symbols :)
Related
I know () has higher precedence than <<, and << has higher precedence than ==, but I want to know why I can't write cout<<a==b; yet can write cout<<(a==b); in C++.
How the compiler translates cout<<a==b; and then shows error?
<< has higher precedence than ==
as you can see here.
The statement
cout<<a==b
is equivalent to
(cout<<a)==b
The expression
cout<<a
returns a stream. This stream is compared to b. If there is no left shift operator for a stream and a or no comparing operator for a stream and b this causes a compiler error
cout<<a==b is similar to (cout<<a) == b as << has higher precedence over ==. Now cout<<a will be syntactically incorrect if the type of a is not supported for <<. Next, if a has an overload for the << operator, it will again be syntactically wrong as the == operator can't operate with std::stream and type of b unless b overloads this compare operator.
But in case of cout<<(a==b), a==b will result in a boolean value. As the << operator support boolean value it is a valid operation.
<< priority is higher than == so it's interpreted as (cout<<a)==b
but = has lower so you can do :
bool t = a == b
This question already has answers here:
What is the "-->" operator in C++?
(29 answers)
Closed 4 years ago.
I have encountered <<++ and >>++ operators many time in`C++, but I don't understand what they are. What is the specific meaning and use of these operators, and how are they different from right shift and left shift operator?
C++ compilers ignore whitespace unless in certain situations such as string literals.
<<++ and >>++ is really just a bit-shift operatior << or >>, followed by an increment operator ++.
Consider this code:
a <<++ b is equivalent to
a<<++b because the spaces are ignored in this context, and then equivalent to
a << ++b (a left shifted by a pre-incremented b)
a << (++b) due to operator precedence. Bit shift operators have lower precedence than incrementation.
There are two separate operators in both cases: left shift (<<), right shift (>>) and increment operator (++).
You can rewrite the following:
a >>++ b
as:
a >> (++b)
I wrote this program:
#include <iostream>
using namespace std;
void unequalityOperator(){
cout << "Running unequalityOperator..." << endl;
bool a = true, b = false;
if ( a != b ) cout << "!=" << endl;
if ( a =! b ) cout << "=!" << endl;
}
int main()
{
unequalityOperator();
system("pause");
return 0;
}
And I was surprised that it run and printed both of the strings. So I tried the same thing with some other binary operators like <=, >=, etc. but it didn't work.
Therefore I would like to understand whether there is a difference between != and =!.
I do know that there are some operators like +=, -=, etc. that work differently and, e.g., the difference between += and =+ is that the addition will occur before or after (respectively) the actual command. And for this reason I suspect that there is difference with the hierarchy in the implementation of these operators, but I am not really sure what.
So please help me understand.
The expression a = !b is an assignment of the value !b into the variable a.
The evaluation of this expression within an if statement is the new value of a.
Since b is set to false and you are assigning !b into a, this value is true.
In first case the != operator is a single inequality operator. In second case it is an assignment operator = with logical not operator !. So in the second case you are assigning not b to a and returning it's result true
This might help to clear things up:
!= : not-equal operator
=! : these are really two operators: assignment operator and unary logical NOT operator
+= : sum-assignment operator
=+ : these are really two operators: assignment operator and unary + operator
-= : difference-assignment operator
=- : these are really two operators: assignment operator and unary - operator
Also, as these were in your question before being edited out:
++= : two operators: postfix increment operator and assignment operator
=++ : two operators: assignment operator and prefix increment operator
I hope you notice the pattern.
For reference:
http://en.cppreference.com/w/cpp/language/operator_precedence
http://en.wikipedia.org/wiki/Operators_in_C_and_C%2B%2B
void show_node_names() { display_flags |= ShowNodeNames; } // what is "|="?
I'm not sure what "|=" does or what it's called.
Any help?
That statement is a bitwise or assignment.
It is equivalent to doing display_flags = display_flags | ShowNodeNames.
In particular, it will set every bit in display_flags to 1 if the corresponding bit in ShowNodeNames is 1.
The |= operator is a compound assignment operator like += or *=, but using the bitwise OR operator. The line
display_flags |= ShowNodeNames;
is equivalent to
display_flags = display_flags | ShowNodeNames;
If you haven't seen the bitwise OR operator, you should read up on it for more details. If you're familiar with it, then you can think of display_flags |= ShowNodeNames; as a way of saying "make all the bits set in ShowNodeNames also set in display_flags."
Hope this helps!
| (which can also be spelt bitor) is the bitwise or operator. It combines the bits of each operand so that each bit of the output is set if the corresponding bit of either operand is set. Compare this with the bitwise and operator, & or bitand, where each bit is set of the corresponding bit of both operands is set.
|= (or or_eq) is the corresponding assignment operator. As with all compound assignment operators, a |= b is equivalent to a = a | b, except that a is only evaluated once. Its effect is to set each bit in a that's set in b, and leave the other bits unchanged.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Operator overloading
I'm making a long awaited return to C++ and there's some basic notation that doesn't really seem to be that prominent in other languages.
If you look at this line of code
cout << "firstvalue is " << firstvalue << endl;
I realise what this does. It write's "firstvalue is x" to the console. x being the value of firstvalue. However, I do not know anything about the "<<" or ">>" double angled brackets. I haven't been able to research them or what they do as I don't know the formal name for them.
My question is, what actually happens (step by step) in the above statement? And what are these "<<" for? I think I understand that cout is a standard library function for writing to the console. However I'm used to either objective-c or dot notation. I do not see what object this "cout" function is a member of.
I can understand printf a little more easily, as at least it provides braces for the arguments. e.g. printf("your string here").
C++ allows operator overloading. That means a user-defined type can define its own behavior on built-in operators. In this case the operators are called: left shift or right shift operators. Those operators have been traditionally been used for bit-shifting, but the standard library repurposes them to symbolize streaming operations.
You can find a list of the available operators in C and C++ here.
In your case you are streaming a string literal and a value of some type into std::cout, which is an object of type std::basic_ostream.
Step-by-Step
After precedence rules have been applied your code looks like this:
((cout << "foobar") << x) << endl;
The compiler will basically transform the object << object expressions into function calls.
operator<<(operator<<(operator<<(cout, "foobar"), x), endl);
Then it will figure out which overload to call. (This is really
tricky. For now it should be sufficient to believe that it simply
looks for an overload of operator<< with matching arguments).
Most of the built-in overloads for basic_ostream are here and here.
The << operator is the "arithmetic left shift" in C++. For example:
3 << 2
evaluates to 12. The reason is that the binary representation of 3 is
00000011
shifting it twice to the left you get
00001100
and the numeric value of the result is 12.
What it has to do this with output? Nothing at all, actually. However in C++ you can redefine the meaning of operators thanks to overloading. The C++ standard library decided to redefine the meaning of the left-shift operator as sort of a "send-to-stream".
So what happens is that
std::cout << "whatever"
returns as value std::cout, but as side effect it outputs the string "whatever".
The operator was chosen because it had a reasonable precedence (overloading cannot change precedence, and you cannot define new operators) and the shape makes it appear somewhat "natural". Note however that the left-shift operator is just a normal operator and for example there is no guarantee about order of evaluation:
std::cout << f() << g() << h();
here the output will be the result of calling f(), followed by the result of calling g() and followed by the result of calling h()... but the functions themselves may be are called in a different order and for example h() could be called first!
So in a sense the "sequence look" of the operator is misleading, because it's about the sequence of output, but not about the sequence of evaluation.
C++17 update
In C++17 this design bug was fixed by special casing << operator to ensure left-to-right evaluation. After C++17 in the expression std::cout << f() << g(); f must be called before g.
The << is an operator, the same way + is an operator and * is an operator. In the way the following are equivalent expressions:
5 + 3 + 2
((5 + 3) + 2)
So are the next two:
std::cout << "Hello" << std::endl
((std::cout << "Hello") << std::endl)
It's just an operator with two operands. For the fundamental types, the << and >> operators are actually known as the left and right shift operators. They perform bitwise shifting. For example, 5 << 1 will shift all the bits in 5 (0101) left one place, to get 10 (1010).
However, as with most other operators, you can overload the shift operators. In the case of the input/output library, the shift operators are overloaded to provide a natural syntax for input and output to a stream. That's because the directionality of the << and >> tokens look like something is flowing one way or the other. With these I/O classes, these operator overloads return a reference to the stream you're performing the operator on so that they can be chained together.
You can overload the shift operators for a particular class by either providing a member function operator<< or operator>> that takes one argument (the operand to the right of the operator). Alternatively, you can provide non-member function with the same names that take two arguments, the two operands of the operator respectively.
They're referred to as stream insertion (or extraction, in the case of istream >>), and are actually a semantic overload of the left-shift and right-shift operators.
So, this:
int x = 1 << 1;
is a bit shift, but this:
std::cout << x;
is a stream insertion. You can write it out explicitly as:
operator <<(std::cout, x);
and get exactly the same result. The conventional format of stream insertion operators (they can be overloaded for user-defined types, so it's not unusual to write your own) is
std::ostream& operator <<(std::ostream&, T value);
The output stream is returned (by reference) so you can chain calls: your example translates as:
operator<< (
operator<< (
operator<<(std::cout, "firstvalue"),
firstvalue
),
std::endl
);
Oh, and ... std::cout (and std::cerr etc.) are not functions: they're global objects. The function here is the overloaded << operator. Think of them as FILE *stdout, *stderr equivalents.
There are some advantages of C++ iostreams over printf et. al:
type-safety: you can't mistakenly print an integer with "%f" and get garbage, because overload resolution automatically selects the std::ostream& operator<<(std::ostream&, double) function at compile time
support for user-defined types: you can write a stream insertion operator for your whizzy new class, and it will just work, everywhere
stream abstraction: you can use the same overloads (so you only write them once) to format to stdout and stderr (cout/cerr), and files (std::ofstream) and strings (std::ostringstream). There's no need to handle printf/fprintf/snprintf separately.
There are also some disadvantages:
performance: there is some penalty to all that abstraction, and the generality of the locale system which is configured at runtime
verbosity: at least for primitive types already supported by printf, the format strings are much terser and more expressive
It's syntactic sugar for the following:
// Let the function 'print' be a renaming of 'operator<<'
// with T being the type of the object you want to print.
std::ostream& print(std::ostream&, const T&);
// 1) Print "first value is" and then return the stream you
// to which to just printed (ie. cout). 2) Use the returned
// stream to chain function calls and print 'firstValue'.
print(print(std::cout, "first value is"), firstValue);