I just created a qstring from a double, but I misplaced the parenthesis. It did compile and the QString was fine in my computer, but the string had a lot of added garbage data data in front of the "1500 m" string I was producing in my friends computer.
My question is: What is actually going on in this codeline. Why doesn't it produce a compiler error?
double distance = 1500;
QString distanceString = QString("%1 m").arg(QString::number(distance), 'f', 1);
No compiler errors, and different behaviour on different computers.
CodePudding user response:
QString("%1 m").arg(QString::number(distance), 'f', 1)
is calling the 3-argument overload
QString::arg(const QString &a, int fieldWidth, QChar fillChar)
So in this case, your parameters will go through implicit conversions:
'f'
converts toint
, which is102
1
converts tochar
and which ends up being theSOH
ASCII character
Becuase these conversions are allowed to happen implicitly, the call to arg
is well-formed and so this is not a compile error.
The function then will do what is designed to do and replace "%1"
with your number, but padded to a length of 102, padded with the unprintable SOH
character. So you end up with a strange looking output.