home sitemap contact

Basic C++ Programming

Expressions in C++

There are 18 levels of operator precedence, listed highest to lowest. Operators at the same level are evaluated left to right unless indicted, Thus, a=b+c means a=(b+c) because + is higher than =, and a-b-c means (a-b)-c. Order of evaluation is undefined, e.g. for sin(x)+cos(x) we cannot say whether sin() or cos() is called first.
The meaning of an expression depends on the types of the operands. (x,y) denotes a comma separated list of 0 or more objects, e.g. (), (x), or (1,2,3,4).

1
X::m           Member m of namespace or class X
::m            Global name m when otherwise hidden by a local declaration
 
2
p[i]           i'th element of container p (array, vector, string)
x.m            Member m of object x
p->m           Member m of object pointed to by p
f(x,y)         Call function f with 0 or more arguments
i++            Add 1 to i, result is original value of i
i--            Subtract 1 from i, result is original value of i
static_cast(x)       Convert x to type T using defined conversions
const_cast(x)        (rare) Convert x to equivalent but non-const T
reinterpret cast<T>(x) (rare, dangerous) Pretend x has type T
dynamic_cast<T>(x)      (rare) Convert base pointer or reference to derived if possible
typeid(x)      (rare) If x is type T, then typeid(x)==typeid(T) (in <typeinfo>)
 
3 (right to left)
*p             Contents of pointer p, or p[0].  If p is type T*, *p is T
&x             Address of (pointer to) x.  If x is type T, &x is T*
-a             Negative of numeric a
!i             Not i, true if i is false or 0
~i             Bitwise compliment of i, -1 - i
(T)x           Convert (cast) object x to type T (by static, const, or reinterpret)
T(x,y)         Convert, initializing with 0 or more arguments
new T          Create a T object on heap, return its address as T*
new T(x,y)     Create, initializing with 0 or more arguments
new(p) T       (rare) Initialize T at address p without allocating from heap
new(p) T(x,y)  (rare) Initialize T with 0 or more arguments at p
new T[i]       Create array of i objects of type T, return T* pointing to first element
delete p       Destroy object pointed to by p obtained with new T or new T()
delete[] p     Destroy array obtained with new T[]
++i            Add 1 to i, result is the new i
--i            Subtract 1 from i, result is the new i
sizeof x       Size of object x in bytes
sizeof(T)      Size of objects of type T in bytes
 
4
x.*p           (rare) Object in x pointed to by pointer to member p
q->*p          (rare) Object in *q pointed to by pointer to member p
 
5
a*b            Multiply numeric a and b
a/b            Divide numeric a and b, round toward 0 if both are integer
i%j            Integer remainder i-(i/j)*j
 
6
a+b            Addition, string concatenation
a-b            Subtraction
 
7
x<<y           Integer x shifted y bits to left, or output y to ostream x
x>>y           Integer x shifted y bits to right, or input y from istream x
 
8
x<y            Less than
x>y            Greater than
x<=y           Less than or equal to
x>=y           Greater than or equal to
 
9
x==y           Equals
x!=y           Not equals
 
10
i&j            Bitwise AND of integers i and j
 
11
i^j            Bitwise XOR of integers i and j
 
12
i|j            Bitwise OR of integers i and j
 
13
i&&j           i and then j (evaluate j only if i is true/nonzero)
 
14
i||j           i or else j (evaluate j only if i is false/zero)
 
15 (right to left)
x=y            Assign y to x, result is new value of x
x+=y           x=x+y, also -= *= /= %= &= |= ^= <<= >>=
 
16
i?x:y          If i is true/nonzero then x else y
 
17
throw x        Throw exception x (any type)
 
18
x,y            Evaluate x and y (any types), result is y

Expressions that don't require creating a new object, such as a=b, ++a, p[i], p->m, x.m, a?b:c, a,b etc. are lvalues, meaning they may appear on the left side of an assignment. Other expressions and conversions create temporary objects to hold the result, which are const (constant). An expression used as a statement discards the final result.

  int a, b, c;
  a+b;         // Legal, add a and b, discard the sum
  a=b=c;       // Legal, assign c to b, then assign the new b to a
  (a+=b)+=c;   // Legal, add b to a, then add c to a
  a+b=c;       // Error, a+b is const
  double(a)=b; // Error, double(a) is const

static_cast<T>(x) converts x to type T if a conversion is defined. Usually the value of x is preserved if possible. Conversions are defined between all numeric types (including char and bool), from 0 to pointer, pointer to bool or void*, istream to bool, ostream to bool, char* to string, from a derived class to base class (including pointers or references), and from type T to type U if class U has a constructor taking T or class T has a member operator U(). A conversion will be implicit (automatically applied) whenever an otherwise invalid expression, assignment, or function argument can be made legal by applying one, except for T to U where U's constructor taking T is declared explicit, for example, the constructor for vector taking int.

  double d; d=static_cast<double>(3);  // Explicit 3 to 3.0
  d=3;                                 // Implicit conversion
  d=sqrt(3);                           // Implicit 3.0, sqrt() expects double
  vector<int> v(5);                    // This constructor is explicit
  v=5;                                 // Error, no implicit conversion
  v=static_cast<vector<int> >(5);      // OK

const_cast<T>(x) allows an object to be modified through a const pointer or reference. It must always be explicit.

  int x=3;
  const int& r=x; r=4;     // Error, r is const
  const_cast<int&>(r)=4;   // OK, x=4
  const int* p=&x; *p=5;   // Error, *p is const
  *const_cast<int*>(p)=5;  // OK, x=5

If x were const, then this code would still be allowed but it is undefined whether x actually changes.

reinterpret_cast<T>(x) turns off normal type checking between int and different pointer types, which are normally incompatible. The only safe conversion is to convert a pointer back to its original type. Conversion is always explicit.

  int x=3, *p=&x; *p=5;             // OK, x=5
  *reinterpret_cast<double*>(p)=5;  // Crash, writing 8 bytes into 4

The expressions T(x) and (T)x apply whatever combination of static, const, and reinterpret casts are needed to convert x to type T.

  const char* s="hello";
  int(*s);                 // static_cast
  (char*)s;                // const_cast
  (const int*)s;           // reinterpret_cast
  (int*)s;                 // reinterpret_cast and const_cast 

Contents | Basic Concept|Statements| Expression |Declaration| Built-in Types| Pointers| Arrays

|Static|Standard Library Type| Programing Organisation|History of C++ |

----------------------------------------You are Visitor No:Visitor Counter by Digits----------------------------------

Quotes of the Day

  • -Winners make goals; loosers make execuses.
  • -Advice is least heeded when most needed.

------------------------------

------------------------------