User forums > Help

Code::Blocks shows different result from hydrooj

(1/1)

gumi:
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;
}

Miguel Gimenez:
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

gd_on:
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]|
--- End code ---

gumi:
Thanks for your answer!! It helps a lot.

Navigation

[0] Message Index

Go to full version