1. Homepage of Dr. Zoltán Porkoláb
    1. Home
    2. Archive
  2. Teaching
    1. Timetable
    2. Bolyai College
    3. C++ (for mathematicians)
    4. Imperative programming (BSc)
    5. Multiparadigm programming (MSc)
    6. Programming (MSc Aut. Sys.)
    7. Programming languages (PhD)
    8. Software technology lab
    9. Theses proposals (BSc and MSc)
  3. Research
    1. Sustrainability
    2. CodeChecker
    3. CodeCompass
    4. Templight
    5. Projects
    6. Conferences
    7. Publications
    8. PhD students
  4. Affiliations
    1. Dept. of Programming Languages and Compilers
    2. Ericsson Hungary Ltd

5. Operators and expressions

Expressions, Expression evaluation

Expressions are formed from operators and values or variables. The most simple expressions are similar to the mathematical expressions.

A + B * C

What is the meaning?

A + (B * C)

Because the precedence of multiplication is higher/stronger than the addition.

What happens, when the operators are on the same precedence level?

A * B / C * D

In FORTRAN77, it was not defined, what is the meaning of this expression:

((A * B) / C) * D
(A * B * D) / C
(A / C) * B * D

…and if A, B, C, D are INTEGERs, the final result could be different.

In modern languages, expressions are defined by precedence and associativity rules.

In C++ associativity is defined by precedence rules. In most precedence groups it is left-to-right, but for unary, ternary and assignment operators they are right-to-left.

Operators in C++

Precedence Operator Description Assoc
1 :: scope qualifier L->R
2 ++ postfix increment L->R
  – – postfix decrement  
  () function call  
  [] array index  
  . struct/union member access  
  -> member access via pointer  
  type() functional cast  
  type{} functional cast (C++11)  
3 ++ prefix increment R->L
  – – prefix decrement  
  + unary plus  
  unary minus  
  ! logical negation  
  ~ binary negation  
  (type) type conversion  
  * pointer indirection  
  & address of  
  sizeof size of type/object  
  new new[] dynamic memory allocation  
  delete delete[] dynamic memory deallocation  
4 .* ->* pointer-to-member L->R
5 * / % multiplication, division, remainder L->R
6 + – addition, substraction L->R
7 « » bitwise left/right shift L->R
8 < <= > >= relational operations L->R
9 (C++20) <=> three-way compar (spaceship) L->R
10 == != equal, not equal L->R
11 & bitwise AND L->R
12 ^ bitwise XOR (exclusive OR) L->R
13 | bitwise OR L->R
14 && logical AND L->R
15 || logical OR L->R
16 ? : conditional expression R->L
17 = assignment R->L
  += –= compound assignment  
  *= /= %=    
  «= »=    
  etc.    
18 throw throw excepsion R->L
19 , sequence operator L->R

There are other operators which are never ambigous:

const_cast  static_cast  dynamic_cast  reinterpret_cast  
typeid  sizeof...  noexcept  alignof

There are alternative spellings for boolean operators:

||   or
&&   and
!    not 

Evaluation of expressions

Although, expressions are defined by precedence and associativity, how the expression is evaluated is implementation defined.

What will print the following program?

1
2
3
4
5
6
7
#include <iostream>
int main()
{
  int i = 1;
  std::cout << "i = " << i << ", ++i = " << ++i << std::endl;
  return 0;
}

Surprisingly, the program can print the following:

$ ./a.out 
i = 2, ++i = 2

In fact, some compilers on some platforms can also print:

$ ./a.out 
i = 1, ++i = 2

The evaluation order may not be defined for expressions.

Exceptions are those operations which are sequence points:

  1. shortcut logical operators ( && || )
  2. conditional operator ( ? : )
  3. comma operator

Also, when a function is called, first the operands should have evaluated, (but parameter evaluation happens in undefined order between the parameters).

Look at the following example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
int f()
{
  std::cout << "f" << std::endl;
  return 2;
}
int g()
{
  std::cout << "g" << std::endl;
  return 1;
}
int h()
{
  std::cout << "h" << std::endl;
  return 0;
}
void func(int fpar, int gpar, int hpar)
{
  std::cout << "(f() == g() == h()) == " << (fpar == gpar == hpar) << std::endl;
}
int main()
{
  func(f(),g(),h());
  return 0;
}
$ g++ -ansi -pedantic -Wall -W op.cpp 
op.cpp: In function ‘void func(int, int, int)’:
op.cpp:19:51: warning: suggest parentheses around comparison in operand of ‘==[-Wparentheses]
   std::cout << "(f() == g() == h()) == " << (fpar == gpar == hpar) << std::endl;
                                                   ^
gsd@ken:~/tmp$ ./a.out 
h
g
f
(f() == g() == h()) == 1

In the example the result of the expression 1 is well-defined. This should be the result regardless of compilers and platforms. However, the order of evaluation of the expression is not defined and may be dependent of the actual platform, compiler, or even compilation flags (e.g. optimizations).

Common errors

In the following we describe a few common mistakes regarding operator precendence of C++ programs.

Wrong precedence

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/*
 * LIKELY BAD!
 */
#include <stdio.h>
int main()
{
  int mask = 0x01;
  if ( mask & 0x10 == 16 )
  {
     printf("This is strange!\n");
  }
  printf("mask = %d, 0x10 = %d,  mask & 0x10 = %d,  mask & 0x10  == 16 = %d\n",
          mask,      0x10,       mask & 0x10,       mask & 0x10  == 16);
  return 0;
}
$ g++ -ansi -pedantic -Wall -W  f.cpp
f.cpp: In function ‘main’:
f.cpp:6:13: warning: suggest parentheses around comparison in operand of ‘&’ [-Wparentheses]
   if ( mask & 0x10 == 16 )
             ^
f.cpp:11:58: warning: suggest parentheses around comparison in operand of ‘&’ [-Wparentheses]
           mask,      0x10,       mask & 0x10,       mask & 0x10  == 16);
                                                          ^
$ ./a.out
This is strange!
mask = 1, 0x10 = 16,  mask & 0x10 = 0,  mask & 0x10  == 16 = 1
$

Bitwise operator precedence is lower than equation relation precedence. Use parentheses to express your intentions.

Correct way

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/*
 * OK!
 */
#include <stdio.h>
int main()
{
  int mask = 0x01;
  if ( (mask & 0x10) == 16 )
  {
     printf("This is strange!\n");
  }
  printf("mask = %d, 0x10 = %d, (mask & 0x10) = %d, (mask & 0x10) == 16 = %d\n",
          mask,      0x10,       mask & 0x10,       (mask & 0x10) == 16);
  return 0;
}
$ g++ -ansi -pedantic -Wall -W  f.c
gsd@Kubuntu-e1:~/ftp$ ./a.out 
mask = 1, 0x10 = 16, (mask & 0x10) = 0, (mask & 0x10) == 16 = 0

Assignment vs equality check

1
2
3
4
5
6
7
8
9
10
11
12
13
/*
 * BAD!
 */
#include <stdio.h>
int main()
{
  int i = 0;
  if ( i = 1 )
  {
    printf("This is strange!\n");
  }
  return 0;
}
$ g++ -ansi -pedantic -Wall -W  f.c
f.cpp: In function ‘main’:
f.cpp:6:3: warning: suggest parentheses around assignment used as truth value [-Wparentheses]
  if ( i = 1 )
  ^
$ ./a.out 
This is strange!

The safe way

If you compare a literal with a value always put the literal on the left side!

1
2
3
4
5
6
7
8
9
10
#include <stdio.h>
int main()
{
  int i = 0;
  if ( 1 = i )
  {
    printf("This is strange!\n");
  }
  return 0;
}
$ gcc -ansi -pedantic -Wall -W  f.c
f.cpp: In function ‘main’:
f.cpp:6:10: error: lvalue required as left operand of assignment
   if ( 1 = i )
          ^

Be care with the compound assignment operators!

1
2
3
4
5
6
7
8
/*
 * LIKELY BAD!
 */
int fun(int par1, int par2)
{
  par1 -= par2 - 1; /* par1 = par1 - (par2-1) */
  return par1;
}

Correct way

1
2
3
4
5
6
7
8
9
/*
 * OK!
 */
int fun(int par1, int par2)
{
  par1 -= par2; /* par1 = par1 - par2 */
  --par1;       /* par1 = par1 - 1    */
  return par1;
}

Missing sequence point

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/*
 * BAD!
 */
#include <stdio.h>
int main()
{
  int t[10];
  int i = 0;
  while( i < 10 )
  {
    t[i] = i++;
  }
  for ( i = 0; i < 10; ++i )
  {
    printf("%d ", t[i]);
  }
  return 0;
}
$ g++ -ansi -pedantic -Wall -W  f.c
f.cpp: In function ‘main’:
f.cpp:9:13: warning: operation on ‘i’ may be undefined [-Wsequence-point]
   t[i] = i++;
           ^
$ ./a.out 
613478496 0 1 2 3 4 5 6 7 8 
$

Do not try to be too C++-ish! Write your intentions in the most simple way. If you need events happenning is sequential order, use sequence points.

Correct way

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/*
 * OK
 */
#include <stdio.h>
int main()
{
  int t[10];
  int i = 0;
  while( i < 10 )
  {
    t[i] = i;
    ++i;
  }
  for ( i = 0; i < 10; ++i )
  {
    printf("%d ", t[i]);
  }
  return 0;
}
Financed from the financial support ELTE won from the Higher Education Restructuring Fund of the Hungarian Government.