Hello.
I've been doing a small application that will go (using only unsigned integer values) from 0 to 4026531840 and print them out.
My code is next:

#include <stdio.h>
#include <inttypes.h>
int main(void){
uint64_t cnt;
for(cnt=0;cnt<=4026531840;cnt++){
printf("%d\n",cnt);
}
}

The only problem that i have is the last numbers are negative (the really last one is -268435456).
I also tried using:

#include <stdio.h>
int main(void){
unsigned long long int cnt;
for(cnt=0;cnt<=4026531840;cnt++){
printf("%d\n",cnt);
}
}

but the problem persists.
I'm using gcc:
Target: x86_64-linux-gnu
gcc version 4.6.1 (Debian 4.6.1-4)
on my linux machine:
Linux mysql 3.0.0-1-amd64 #1 SMP Sat Aug 27 16:21:11 UTC 2011 x86_64 GNU/Linux
Any ideas?

Dani AI

Generated

The output turned negative because the printf format didn’t match the integer type — that’s undefined behavior. The specific value you saw, -268435456, is exactly the signed 32‑bit interpretation of 4026531840 (0xF0000000): 4026531840 − 2^32 = −268435456. In other words, the bytes for the large unsigned value were being interpreted as a signed 32‑bit number.

’s quick fix worked because using a matching unsigned format stops that mismatch. For truly portable code, prefer the inttypes.h macros for fixed-width types: use PRIu64 when printing a uint64_t (or PRIu32 for uint32_t) so your format always matches the typedef on the target platform. Example:

#include <inttypes.h>
#include <stdio.h>

uint64_t cnt = 4026531840;
printf("%" PRIu64 "\n", cnt);

Build with warnings enabled so the compiler catches format/type mismatches (for example: gcc -std=c11 -Wall -Wextra -pedantic file.c). If the range you need truly stops at 4026531840, a uint32_t is sufficient and avoids confusion; use PRIu32 or %u when appropriate.

Also note a practical point: printing billions of lines to a terminal is extremely slow. If you really need that many numbers, write to a file with buffered I/O or generate them in a more compact/binary form instead of one line per number.

Recommended Answers

All 2 Replies

You're printing the value with %d, which is limited to signed int. The C99 specifier for unsigned long long is %llu:

#include <stdio.h>

int main(void)
{
    unsigned long long int cnt;
    
    for (cnt = 0; cnt <= 4026531840; cnt++)
        printf("%llu\n", cnt);
}
commented: Demonstrates an amazing ability to quickly solve problems not easily solved by others. Shows great depth of knowledge and a solid background based on in depth studies. +5

Thanks. Problem solved.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.