Author Topic: Code::Blocks shows different result from hydrooj  (Read 1394 times)

Offline gumi

  • Single posting newcomer
  • *
  • Posts: 2
Code::Blocks shows different result from hydrooj
« on: August 23, 2022, 09:41:19 am »
Hi, I'm trying to make codeblocks have the same environment as hydro oj does. Because codeblocks seem can tolerate more fault. For example, the code shown below is converting binary to decimal. However, seems like codeblocks can initialize the variable and make the correct result.
Take input 101 for example, the output should show a random number rather than 5.
Can anyone tell me how to get rid of this kind of automatic initialization?


#include <iostream>
using namespace std;

int main() {
    long long bin;
//    int ans = 0;
    int ans; // can work without initializing to 0


    cin >> bin;

    long long num = bin;
    long long x = 0;
    int y = 0;
    int a = 0;
    int b = 1;

    while (num > 0) {
        x = num / 10;
        y = num % 10;
        ans = b * y + ans;
        num = x;
        b = b * 2;
    }

    cout << ans << endl;

    return 0;
}


Offline Miguel Gimenez

  • Developer
  • Lives here!
  • *****
  • Posts: 1553
Re: Code::Blocks shows different result from hydrooj
« Reply #1 on: August 23, 2022, 12:42:10 pm »
If you do not initialize a local variable it will contain and undetermined (not random) value. Differences between compilers are expected.

This said, your question is OT here. Look at C++ or related compiler forums.

Default initilalization

Offline gd_on

  • Lives here!
  • ****
  • Posts: 796
Re: Code::Blocks shows different result from hydrooj
« Reply #2 on: August 23, 2022, 01:03:39 pm »
This is not related to codeblocks. Codeblocks is NOT a compiler, but an Integrated Development Environment. It can use many other compilers than gcc/g++.
Nevertheless, your result is normal because you have used the debug mode apparently. This mode in gcc makes some initialisations for you.
If you try the release mode, the result is not the same, because here ans is not initialised : indicated by a warning :
Code
main.cpp|26|warning: 'ans' may be used uninitialized [-Wmaybe-uninitialized]|

Windows 11 64 bits (23H2), svn C::B (last version or almost!), wxWidgets 3.2.4 (tests with 3.3), Msys2 Compilers 13.2.0, 64 bits (seh, posix : gcc, g++ and gfortran in C:\msys64\mingw64) or 32 bits (dwarf2, posix  in C:\msys64\mingw32).

Offline gumi

  • Single posting newcomer
  • *
  • Posts: 2
Re: Code::Blocks shows different result from hydrooj
« Reply #3 on: August 24, 2022, 08:02:56 am »
Thanks for your answer!! It helps a lot.