Tan Jia Ming
Tan Jia Ming

Reputation: 465

Same code but different output in Netbeans C/C++ Project

I came across this weird situation in Netbeans C/C++. Here is the situation: In my project explorer, under Source Files, I have main.c and problem3.c

In main.c

    #include <stdio.h>
    #include <stdlib.h>

    // long BigNumber(){
        // return 600851475143;
    // }


    int main(int argc, char* argv[]) {
        printf("%lu", BigNumber() );

        return (EXIT_SUCESS);
    }

In problem3.c

     long BigNumber(){
         return 600851475143;
     }

My case is, when I use BigNumber() from problem3.c, it will output 403282979527, which is incorrect. But if I use BigNumber() from main.c, it will print 600851475143.

Can anyone explain the magic behind? Is it because of the platform, or tools such as make? I'm using Windows 7 32-bit, NetBeans 7.3.1, with MinGW.

Upvotes: 0

Views: 158

Answers (1)

Sam Cristall
Sam Cristall

Reputation: 4387

This is actually overflow as Windows 32-bit follows the LP32 or 4/4/4 model where int, long and pointer are all 32-bits (4 bytes) long and the number you are storing is larger than 32-bits, signed or not. The fact that it works at all in the first case is actually just a coincidence. Likely the linking step caused by moving it to the other file "brings out" some other behavior that causes the problem you are seeing. gcc even warns of overflow here.

You have a few options, but a simple one is to use int64_t instead of long (this is why all those intxx_t types exist after all!). You should also use a LL suffix on the literal to inform the compiler that it is a long long literal, and also change your printf to use "llu" instead of "lu" (long long again)

The fix altogether:

#include <stdio.h>
#include <stdlib.h>

int64_t BigNumber() {
    return 600851475143LL;
}

int main(int argc, char* argv[]) {
    printf("%llu", BigNumber() );
    return 0;
}

You should be able to safely move this function, as it is now well defined.

Upvotes: 1

Related Questions