Mister-3
Mister-3

Reputation: 27

Unsigned long in C

I tried to put an unsigned INT just to play around with it but it doesn't seem to work I don't see where the problem could be here is the code :

#include <stdio.h>

void main()
{
     unsigned long nou=2200000000UL;
     
    printf("the number is %d" ,nou);

}

It return : the number is -2094967296 as The maximum value of INT = 2147483647 it's normal it don't give the good output but when I try with :

  #include <stdio.h>
    
    void main()
    {
         unsigned long nou=2100000000;
         
            printf("the number is %d" ,nou);
    
    } 

The correct value gets printed out, I don't know why the unsigned command doesn't work.

Upvotes: 0

Views: 2577

Answers (1)

DannyNiu
DannyNiu

Reputation: 1513

You should change %d in the printf call to %u (and %lu when using unsigned long).

According to the application binary interface on most systems, signed and unsigned integers are both passed in general purpose registers whenever possible. Their signedness is determined by the subroutine that recieves them.

  • %d and %i are decimal output for **signed** int;

  • %u is the decimal output for **unsigned** int;

  • %o, %x, and %X are octal, hexadecimal lowercase, and hexadecimal uppercase output for unsigned integers as well.


Appendix

As noted in the comments, there are other flags and modifier letters needed for integers whose ranks are greater than int, integers whose ranks are lesser than int are promoted in variadic functions.

There are some good online sources to consult for the usage of printf.

  • cplusplus.com and cppreference.com and alikes are good for beginners,

  • ISO C drafts are good when you need a free reference as close to authoritative as possible. They are available at http://open-std.org/JTC1/SC22/WG14/www/projects

  • The POSIX standards and man page on various Unix and Unix-like systems contain extansions that are recognized in these operating system environments.

Upvotes: 2

Related Questions