Search code examples
c++visual-studiointegerwindows-10visual-studio-2019

C++ give me strange result


I have a very strange result running the following C++ code:

#include <iostream>

using namespace std;

int main()
{
    int c[]={49,46,48,46,51};
    int p=0;
    for(int i=0;i<5;i++)
         p =p*100+c[i];

    cout << "Hello World! p=" <<p<< endl;
    return 0;
}

Hello World! p=651517355

However, the expected results is 4946484651.

Even if I change the data type to long integer, the same wrong result was given.

My environment is,

windows 10, Qt Creator 4.14.1 (Qt 5.15.2 MSVC2019 64bit)
cl -c -nologo -Zc:wchar_t -FS -Zc:rvalueCast -Zc:inline -Zc:strictStrings -Zc:throwingNew -Zc:referenceBinding -Zc:__cplusplus -Zi -MDd -W3 -w34100 -w34189 -w44996 -w44456 -w44457 -w44458 -wd4577 -wd4467 -EHsc /Fddebug\aa.vc.pdb -DUNICODE -D_UNICODE -DWIN32 -D_ENABLE_EXTENDED_ALIGNED_STORAGE -DQT_QML_DEBUG -I..\aa -I. -I..\..\..\Qt\5.14.0\msvc2017\mkspecs\win32-msvc -Fodebug\ @C:\Users\guest\AppData\Local\Temp\main.obj.20080.15.jom
main.cpp

Solution

  • On many platforms (including yours, it would appear), both int and long int are 32-bit integers, which cannot hold the value 4946484651. (The Standard mandates only that long int be no shorter than int and at least 32 bits wide.)

    You need to use long long int for p or, better still, use the explicit int64_t type:

    #include <iostream>
    #include <cstdint>
    
    int main()
    {
        int c[] = { 49,46,48,46,51 };
        int64_t p = 0;
        for (int i = 0; i < 5; i++)
            p = p * 100 + c[i];
    
        std::cout << "Hello World! p=" << p << std::endl;
        return 0;
    }
    

    Output:

    Hello World! p=4946484651