10

This question is quite clear. What are the differences between an int, an uint8_t, and an uint16_t. I know it has to do with bytes and memory but can someone clarify me a bit?

Things I want to know:

1- How much memory does each take.

2- When to use what.

3- In the end of the day, are they that different?

1
  • 1
    Beware that the compiler does not do arithmetic with anything smaller than int. E.g. (uint8_t) 200 + (uint8_t) 200 does not overflow: the terms are promoted to int before the addition and the result is (int) 400. Nov 1, 2016 at 21:55

1 Answer 1

13

You can decipher most of them yourself.

  • A u prefix means unsigned.
  • The number is the number of bits used. There's 8 bits to the byte.
  • The _t means it's a typedef.

So a uint8_t is an unsigned 8 bit value, so it takes 1 byte. A uint16_t is an unsigned 16 bit value, so it takes 2 bytes (16/8 = 2)

The only fuzzy one is int. That is "a signed integer value at the native size for the compiler". On an 8-bit system like the ATMega chips that is 16 bits, so 2 bytes. On 32-bit systems, like the ARM based Due, it's 32 bits, so 4 bytes. Of the three it is the only one that changes.

Personally I rarely use int and always use uint8_t etc., since the variable type is the same no matter what architecture you compile for. When you use int you can run into problems if you had a program that worked fine on a 32-bit ARM but then doesn't work right on an 8-bit ATMega, since the int can only store a fraction of the range of numbers on the 8-bit system compared to the 32-bit system.

5
  • Can I make an uint8_t array?
    – Dat Ha
    Nov 1, 2016 at 20:06
  • You can make an array of any data type.
    – Majenko
    Nov 1, 2016 at 20:07
  • Can I use it like this too: uint8_t function()
    – Dat Ha
    Nov 1, 2016 at 20:37
  • 2
    Yes. uint8_t is the same as "byte" or "unsigned char".
    – Majenko
    Nov 1, 2016 at 20:37
  • 2
    If you need negative values, you need to use signed integers. E.g. int16_t.
    – Gerben
    Nov 1, 2016 at 21:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.