1

I'm starting with c programming and I think I'm not sure about the use of unsigned variables. I know uint8_t is an unsigned 8 bit integer type, and that means that it cannot be negative, thus with all 8 bits set aside for positive numbers, this represents a number from 0 to 255. But I don't know why if I write this:

int main() {

 uint8_t value [4]; 

 printf("\nvalue:\t%" PRIu8 "", value[0]);
 printf("\nvalue:\t%" PRIu8 "", value[1]);
 printf("\nvalue:\t%" PRIu8 "", value[2]);
 printf("\nvalue:\t%" PRIu8 "", value[3]);
 printf("\n");

}

I obtain different results every time I made: ./test:

test@test:~/Desktop$ ./test

value:  48
value:  99
value:  13
value:  193

test@test:~/Desktop$ ./test

value:  176
value:  76
value:  71
value:  0

test@test:~/Desktop$ ./test

value:  64
value:  13
value:  5
value:  175

Why I get a different numbers in value[x]?

  • 5
    Possible duplicate of [How does an uninitialized variable get a random value?](http://stackoverflow.com/questions/17216663/how-does-an-uninitialized-variable-get-a-random-value) – Gerhardh Jan 26 '17 at 21:08
  • `static uint8_t ...` :) But it's another story (the proper answers are flying around). – 0andriy Jan 26 '17 at 22:03
  • 1
    An upvoted answer, but you did not say what values you would expect to be printed. – Weather Vane Jan 26 '17 at 22:17

1 Answers1

4

It is undefined behaviour to read the value of an uninitialized variable. In other words, the rules of the C programming language do not describe or constrain how your program should behave.

To make your program well-behaved, you need to give the variable a value before reading it, for example:

uint8_t value[4] = { 3, 19, 26, 1 };
Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084