Re: printf() print arguments in reversed order

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



It is undefined behavior.

The evaluation of three parameters in question is (at the moment) unsequenced.
Since each of them  contains a function call, the three function calls are also
unsequenced. The modify-and-read operations inside the function calls are
unsequenced relative to each other. Hence the UB.

WG21 N4618 1.9 Program execution [intro.execution]
> 18 ... If a side effect on a memory location (1.7) is unsequenced relative to
> either another side effect on the same memory location or a value computation
> using the value of any object in the same memory location, and they are not
> potentially concurrent (1.10), the behavior is undefined. ...
(Here the 'memory location' is the lvalue `i`.)


------------------				 
Best regards,
lh_mouse
2016-12-08

-------------------------------------------------------------
发件人:topher <topherchen@xxxxxxxxx>
发送日期:2016-12-08 14:43
收件人:gcc-help
抄送:
主题:printf() print arguments in reversed order

Hello,

I'm trying the following code and see some behavior I don't understand.

#include <string>
#include <cstdio>
#include <sstream>

using namespace std;

struct StaticName {
    string getName() {
        static int i = 0;
        name.clear();
        ostringstream oss;
        oss << ++i;
        name += oss.str();
        return name;
    }
    static string name;
};
string StaticName::name = "";

int main(int argc, char* argv[]) {
    StaticName sn;
    printf("name1=%s, name2=%s, name3=%s\n",
           sn.getName().c_str(), sn.getName().c_str(), sn.getName().c_str());
    return 0;
}

The executable built by g++ 4.8.5 prints "name1=3, name2=2, name3=1".
However, executable built by clang++ 3.8.0 prints "name1=1, name2=2,
name3=3", which is what I expected.
Is there any undefined behavior in my code?

Thanks!






[Index of Archives]     [Linux C Programming]     [Linux Kernel]     [eCos]     [Fedora Development]     [Fedora Announce]     [Autoconf]     [The DWARVES Debugging Tools]     [Yosemite Campsites]     [Yosemite News]     [Linux GCC]

  Powered by Linux