0

please, if somebody can explain. I have some questions about habit of pow(a, b) function in c++ (IDE Visual Studio 2019). During exercises I found strange habit of x++ and ++x in library function pow(a,b), precisely, I can't understand why such results:

int x=1;
cout << "pow(x++, x) = " << pow(x++, x) << endl; 

all right in this case, result is:

pow(x++, x)=1

but in case of:

int x=1;
cout << "pow(x, x++) = " << pow(x, x++) << endl; 

result is:

pow(x, x++)=2

why postcrement effects so differently?

additional cases:

int x=1;
cout << "pow(++x, ++x) = " << pow(++x, ++x) << endl; 

result is:

pow(++x, ++x)=27

it's clear, but if:

int x=1;
cout << "pow(++x, x++) = " << pow(++x, x++) << endl; 

result is:

pow(++x, x++)=3

another case:

int x=1;
cout << "pow(x++, ++x) = " << pow(x++, ++x) << endl; 

result is:

pow(x++, ++x)=8

and one more:

int x=1;
cout << "pow(x++, x++) = " << pow(x++, x++) << endl; 

result is:

pow(x++, x++)=2

in some variations results are as expected, but in some variations - not expected.

  • 2
    There should many dupes on the line of https://stackoverflow.com/questions/949433/why-are-these-constructs-using-pre-and-post-increment-undefined-behavior and some more specific about the order of evaluation of function arguments not being determined. Also, while not the issue here, `pow` accepts and returns floating-point values. – Bob__ Jul 07 '21 at 06:10
  • Does this answer your question? [Why are these constructs using pre and post-increment undefined behavior?](https://stackoverflow.com/questions/949433/why-are-these-constructs-using-pre-and-post-increment-undefined-behavior) – phuclv Jul 07 '21 at 06:20
  • @phuclv Things are not clearly undefined here as the reference makes it seem. I think that VS 2019 compiles in C++17 mode by default, and there the function argument evaluations are indeterminately sequenced, not unsequenced. Most, if not all of, the examples are well-defined, albeit unspecified. – j6t Jul 07 '21 at 06:54

0 Answers0