Is this Undefined Behavior?

I would like to know if the code below is well-defined.

I am still quite confused about sequence points, and it looks to me that i is modified twice on lines 19 and 22.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>

int inc1(int &i)
{
    i += 1;
    return i;
}

int & inc2(int &i)
{
    i += 1;
    return i;
}

int main()
{
    int i=0;

    i = inc1(i);
    std::cout << i << '\n';

    i = inc2(i);
    std::cout << i << '\n';
}


Edit: changed example.
Last edited on
I would like to know if the code below is well-defined.
Yes, I don't see where a problem could occur.

it looks to me that i is modified twice on lines 19 and 22.
Well, it's increased and assigned. There's no problem that a variable is assigned to itself
The applicable sequence point rules (C++98) are:

2) When calling a function (whether or not the function is inline and whether or not function call syntax was used), there is a sequence point after the evaluation of all function arguments (if any) which takes place before execution of any expressions or statements in the function body

3) There is a sequence point after the copying of a returned value of a function and before the execution of any expressions outside the function.

http://en.cppreference.com/w/cpp/language/eval_order (at the bottom of the page)


So, there is no undefined behaviour in C++98.
Topic archived. No new replies allowed.