There are several reasons why a variable may not support a value. Although some of them are secret and difficult to debug, some of the most common reasons include:
Variable Modified by Interrupt
//---in main()--- unint8_t rxByte = 0; printf("%d", rxByte); //prints "0" //---later in Uart0_Rx_Handler()--- rxByte = U0RXREG; //rxByte set to (for example) 55 //---later in main()--- printf("%d", rxByte); //still prints "0"!!!
If a variable is modified by an interrupt handler, it must be declared mutable. Volatile lets the compiler know that a variable can be changed asynchronously and that it should not use a cached copy in the register.
//---in main()--- volatile unint8_t rxByte = 0; printf("%d", rxByte); //prints "0" //---later in Uart0_Rx_Handler()--- rxByte = U0RXREG; //rxByte set to 55 //---later in main()--- printf("%d", rxByte); //corectly prints 55
Array restriction prevention
There are no checks in C to ensure that you don't go beyond the array.
int array[10]; int my_var = 55; printf("%d", my_var); //prints "55" for(i=0; i<11; i++) // eleven is one too many indexes for this array { array[i] = i; } printf("%d", my_var); // prints "11"!!!
In this case, we go through the loop 11 times, which is one index more than the array. In most compilers, this will overwrite the variables declared after the array (anywhere on the page, they do not even need to be declared on the next line). This scenario can occur in many different situations, including multidimensional arrays and stack corruption.
Forget about dereferencing a pointer
While it is trivial, forgetting the asterisk on the pointer when making assignments, the variable will not be set correctly
int* pCount; pCount = 10; //forgot the asterisk!!! printf("%d", *pCount); //prints ??
Masking a variable with the same name
Reusing a variable name in the inner scope (for example, inside an if / for / while block or inside a function) hides a variable with the same name elsewhere.
int count = 10; //count is 10 if(byteRecevied) { int count = U0RXREG; //count redeclared!!! DoSomething(count); printf("%d", count); //prints "55" } printf("%d", count); //prints "10"