Home > database >  Weird order of execution in Qt C
Weird order of execution in Qt C

Time:11-30

Apologies if this has been asked before but I could not find any answers. If someone can enlighten me what is going on here?

I was playing around with Qt and standard c . So the payground code below didn't do what I expected. Is that related QCoreApplication queue? I expected the sequence of 1 2 3 4 5 before array size is: 5 and as the first operation executed?

Thank you for the help.

#include <QCoreApplication>
#include <QDebug>
#include <iostream>
#include <algorithm>
#include <array>

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    qDebug() << "hello";

    std::array<int, 5> vals {1,2,3,4,5};
    for (auto& v: vals) {
        qInfo() << v;
    }
    
    auto* vals_ptr = vals.data();
    qInfo() << *(vals_ptr 1);
    qInfo() << *(vals_ptr 2);

    auto print = [](const int& n) { std::cout << " " << n; };
    std::for_each(vals.cbegin(), vals.cend(), print);
    qInfo() << "array size is: " << vals.size();

    return a.exec();
}

Output below

 1 2 3 4 5hello
1
2
3
4
5
2
3
array size is:  5

CodePudding user response:

From docs on qInfo:

Calls the message handler with the informational message message. If no message handler has been installed, the message is printed to stderr. Under Windows, the message is sent to the console, if it is a console application; otherwise, it is sent to the debugger. On QNX the message is sent to slogger2. This function does nothing if QT_NO_INFO_OUTPUT was defined during compilation.

In other words, qInfo writes to stderr. std::cout writes to stdout. Thats two seperate streams. Only within one stream the output is in order. Due to buffering the streams can be interleaved.

CodePudding user response:

Different streams have separate buffers and different buffering strategies. If they ultimately output to the same place (i.e. your terminal), and you carelessly mix them, your output is likely to become jumbled, because the moment when any particular buffer buffer is flushed can be unpredictable (or simply inconvenient). To avoid this, use << std::flush each time you are switching streams.

qDebug() << "hello" << std::flush; // different stream coming forth
for (auto& v: vals) {
    qInfo() << v; // continuing with qInfo(), no flush here
}
qInfo() << flush; // different stream coming forth
  • Related