What Are Integer Literal Type? And How They Are Stored?

后端 未结 4 1378
逝去的感伤
逝去的感伤 2020-12-21 17:44

I have just started learning C and a question has bugged me for a while now. If I write

int i = -1;
unsigned int j = 2;
unsigned int k = -2;
<
4条回答
  •  清歌不尽
    2020-12-21 18:04

    In C99 and C11

    If you want to specifies the type of your integer you can use an integer constant:

    You can write integer with decimal, octal or hexa representation:

    int decimal = 42; // nothing special
    int octal = 052; // 0 in front of the number
    int hexa = 0x2a; // 0x
    int HEXA = 0X2A; // 0X
    

    Decimal representation:

    By default, the type of -1, 0, 1, etc. is int, long int or long long int. The compiler must peak the type that can handle your value:

    int a = 1; // 1 is a int
    long int b = 1125899906842624; // 1125899906842624 is a long int
    

    That only work for signed value, if you want unsigned value you need to add u or U:

    unsigned int a = 1u;
    unsigned long int b = 1125899906842624u;
    

    If you want long int or long long int but not int, you can use l or L:

    long int a = 1125899906842624l;
    

    You can combine u and l:

    unsigned long int a = 1125899906842624ul;
    

    Finally, if you want only long long int, you can use ll or LL:

    unsigned long long int a = 1125899906842624ll;
    

    And again you can combine with u.

    unsigned long long int a = 1125899906842624ull;
    

    Octal and Hexadecimal representation:

    Without suffix, a integer will match with int, long int, long long int, unsigned int, unsigned long int and unsigned long long int.

    int a = 0xFFFF;
    long int b = -0xFFFFFFFFFFFFFF;
    unsigned long long int c = 0xFFFFFFFFFFFFFFFF;
    

    u doesn't differ from decimal representation. l or L and ll or LL add unsigned value type.


    This is similar to string literals.

提交回复
热议问题