Operators & Expressions
C's Toolbox, Upgraded
If C gave you a solid toolbox β hammers, screwdrivers, wrenches β C++ took that same toolbox and added a power drill, a laser level, and a label maker. Every operator you know from C works exactly the same in C++. But C++ introduces a handful of new ones that make the language more expressive.
Let's start with the familiar, then meet the newcomers.
The Familiar Operators
All of C's operators carry over unchanged:
- Arithmetic:
+,-,*,/,%(modulo) - Comparison:
==,!=,<,>,<=,>= - Logical:
&&(AND),||(OR),!(NOT) - Bitwise:
&,|,^,~,<<,>> - Assignment:
=,+=,-=,*=,/=,%=,&=,|=,^= - Increment/Decrement:
++,--(prefix and postfix) - Ternary:
condition ? valueIfTrue : valueIfFalse
These work identically to C. No surprises here.
Familiar Operators in C++
New Kid: Scope Resolution (::)
The :: operator is C++'s way of saying "I mean this specific one." It resolves ambiguity when names collide β like having two people named "Alex" in a room and specifying "Alex from accounting" vs "Alex from engineering."
You'll see :: everywhere: accessing namespace members (std::cout), defining class methods outside the class, and reaching global variables hidden by local ones.
Scope Resolution Operator (::)
Stream Operators: << and >>
Here's where C++ does something clever. In C, << and >> are bitwise shift operators β they shift bits left or right. C++ keeps that behavior for integers, but overloads them for I/O streams.
Think of << as "push data onto the stream" (like putting items on a conveyor belt heading to the screen) and >> as "pull data off the stream" (like picking items off a belt coming from the keyboard).
cout << Chaining β Putting Items on the Belt
<< and >> are bitwise shift in C, but in C++ they're overloaded for I/O with streams. Context matters! When used with cout/cin, they're stream operators. When used with integers, they're still bitwise shift. The compiler knows which to use based on the operand types.new and delete β Manual Memory C++ Style
C uses malloc() and free(). C++ introduces new and delete β operators (not functions!) that allocate memory and call constructors/destructors. They're type-safe and cleaner, though modern C++ prefers smart pointers over raw new/delete.
new and delete
sizeof and typeid β Inspecting Types
sizeof works just like C β it gives you the size in bytes. But C++ adds typeid (from <typeinfo>) which lets you inspect the actual type of a variable at runtime. This is especially useful with auto when you're not sure what the compiler deduced.
sizeof and typeid
Note: typeid().name() output is compiler-dependent. GCC gives short codes like i (int), d (double), c (char), b (bool). MSVC gives more readable names. Either way, it tells you what the compiler thinks the type is.