Jack
Jack

Reputation: 16724

Unexpected output printing long number

Trying to print a long in C++ on 32-bit machine. I'm getting an unexpected output.

From this code:

long n = 5330111323L;
printf("n = %ld\n", n);
printf("can print? %s\n", LONG_MAX < 5330111323L ? "yes" : "NO");
printf("LONG_MAX = %ld\n", LONG_MAX);

I'm getting this:

enter image description here

The C# output is fine.

This:

long n = 5330111323L;
    Console.WriteLine(n);

print:

5330111323

Both use 32-bit compilers. Why am I getting this C++ output?

Upvotes: 0

Views: 209

Answers (5)

Pierre
Pierre

Reputation: 1174

There is a mistake in the condition, it should be :

LONG_MAX > 5330111323L ? "yes" : "NO"

n can be (correctly) printed if it is lower than LONG_MAX, because in all cases, n will be lower or equal to LONG_MAX if n has been declared as long.

edit: note you can use >= too

Upvotes: 2

SACHIN GOYAL
SACHIN GOYAL

Reputation: 965

What do you think , which is bigger 5330111323(user input) or 2147483647(LONG_MAX)?

You are actually trying to print a value which is outside the long range on your system Which is an invitation to undefined behavior .

BTW , Improve below condition in your program .

printf("can print? %s\n", LONG_MAX > 5330111323L ? "yes" : "NO"); //

Upvotes: 0

Paulo1205
Paulo1205

Reputation: 944

In C++, integer literal constants that are to large to fit their original types can be automatically interpreted as a longer type, even if they have the wrong suffix.

#include <iostream>

int main(){
    auto a=9876543210;  // ‘L’ or ‘LL’ suffix missing.
    int  b=a;           // Not even a warning
    int  c=9876543210;  // warning: "implicit constant conversion", even without suffix!
    std::cout << a << '\n' << b << '\n' << c << '\n';
}

Upvotes: 0

SergeyA
SergeyA

Reputation: 62603

sizeof(long) is not fixed anywhere and there is no even 'customary' size for it, and using this type is actually not recommended (there are checkers which even issue an error every time long is used). In particular, on your system it is clear long is 32 bit in size.

On a side note, size of the long (or any other non-pointer type for this matter) has no relationship to 32 vs 64 bit mode.

On the third note, your check is logically incorrect. You should be printing 'yes' when LONG_MAX is bigger than the number.

Upvotes: 1

NathanOliver
NathanOliver

Reputation: 180955

In C# long is a 64 bit data type. It doesn't matter that you compile on 32 bits it is still 64 bits in size. In C++ All we know about long is that it has to hold as much or more than an int and it is at least 32 bits. If you use a long long in c++ that is guaranteed to be at least 64 bits which will match what you have in C#. Again it is 64 bits even if you compile in 32 bits in C++.

Upvotes: 1

Related Questions