How to initialize a variable

30 Views Asked by At

I want to store in n a 32-bit integer number. How should I initialize the variable n?

With unsigned int n or with int n?

Can someone tell me the difference between these two ?

The sign of the number stored in n does not matter. It is only important to store a 32 bit number.

1

There are 1 best solutions below

1
Reinhard Männer On

I probably don't understand your question, but I will try an answer.
You talk about int and unsigned int, thus I assume you use C as programming language. The data types of C are described here.
I assume you talk about a 32 bit architecture that stores int and unsigned int with 32 bits.
To initialize such a variable means to allocate memory for it, in this case a 32 bit word. Now, C can be considered as a statically typed language, as explained here. This means that the compiler checks if a value of the correct type (int or unsigned int) is to be assigned to a variable.
So the first question is how your 32 bit number is to be stored in the allocated memory of your var. If this is done in your code (and not, e.g. by direct memory access), your 32 bit number has to have the right type (int or unsigned int). It is however possible to change the type, e.g. from unsigned int to int, by type casting, see here.
The real question is, how your code interprets the 32 bit number. If it is int or unsigned int, you should initialize it as such. If something else, e.g. bit-packed values, I would use unsigned int.
Note that bit-packed values are different from C bit fields, as explained here.