views:

1319

answers:

11

Hi,

How do I determine if an integer is unassigned?

int i; /* no assignment */

if (/* conditional statement here to check if int i is unassigned or not */) {
   printf("Integer is unassigned!\n");
} else {
   printf("Integer is assigned!\n");
}

Language: C

Best regards, Timothy

+15  A: 

You can't. It will have "undefined" content, meaning it'll contain what ever happens to be in that memory location at that time.

. . . unless i is declared at the global scope, then it will be initialised to Zero.

Binary Worrier
@Kenny: "unless i is declared" is actually what I wanted to say, as "i" is the variable we're talking about, thanks.
Binary Worrier
Actually, I think that one could argue that even a static variable is unassigned (it is of course zero initialised) if you don't explicitly initialise it.
anon
@Neil: You're now wandering into a world of semantics. EVERYONE (including me) knows what it means to assign a value. EVERYONE also knows what it means to initialise a variable. Now, ask EVERYONE "Whats the different between assignment and initialisation?" and watch them flounder (my own head is starting to hurt about now too).
Binary Worrier
I take your point. But I was assuming the OP meant by "unassigned" something like "have I explicitly done something which gives this variable a known value". In which case both static and local variables that are not explicitly initialised are "unassigned".
anon
@Neil: This is true, and it's a nice distinction between the two.
Binary Worrier
+7  A: 

C doesn't intrinsically support this - just like it doesn't intrinsically support bounds checking on arrays. It's a trade-off between speed/efficiency and safety.

In general... initialize your variables.

Amber
+4  A: 

If i is global or static, its value will be 0, otherwise its value can be anything and there is no way to find out whether it is garbage or not.

qrdl
A: 

Usually variables are set to 0 by the C library, but not necessarily.

But basically, you can't. Assign them a default value in the definition, for instance: int i = 0; /* Or what ever value you know won't be used elsewhere */

Then if you run some code and want to check if the value was set there, you can compare to your initial value.

Makis
See this message for example:http://gcc.gnu.org/ml/gcc-help/2007-07/msg00097.html
Makis
And in saying so, I didn't mean anyone should trust that this happens. If you need a variable to be 0, specifically initialize it to that value!
Makis
+9  A: 

It's very simple. You know it is unassigned because you did not initialise it.

anon
A: 

In C, an integer takes on an undefined value when it is created. This means that if your first use of that integer comes from a register/memory location/device with a 5893872 in it, that's the value of that integer. (Mileage varies for debug/release compilation.)

The usual method of dealing with this is to use a nonsensical default:

int number_of_widgets = -1;

...or a flag to indicate its state:

int number_of_widgets;
int number_of_widgets_assigned = 0;

if (number_of_widgets_assigned)
  do something
else
  do something else
number_of_widgets_assigned = 1;

There is no other way to detect whether something has been assigned to - unless you want to get into the debugging features of your hardware and I suspect that is not what this conversation is about.

+1  A: 

As all previous answers, there is no way to detect that at runtime. However, almost any static code analysis tool with warn you for unassigned variables.

KIV
+1  A: 

You may be able to ask for compiler warnings if you use uninitialized values. They're not wholly reliable, however - you get the occasional false positive where the DFA isn't as clever as you'd hope, and maybe occasional false negatives (I'd hope not, but I promise nothing).

For GCC:

-Wuninitialized -O1

If you want to write conditional code:

int a = 3;
int b;
int *p = (rand() > RAND_MAX/2) ? &a : &b;
if (is_uninitialized(*p)) // blah

then you're out of luck. Unlike some dynamic languages, C has no concept of "the undefined value". If a variable is not initialized, it isn't given some special value which can be tested for later. It's not given a value at all, so it's undefined what happens when you use the variable.

Steve Jessop
+1  A: 

Using a variable before intialization (or assignment) is serious cause of errors. You can not reliably check it at runtime, but you can detect it during or before compilation.

I suggest not to check it inside the code. Because this is likely to cause compiler warnings (Variable 'i' is used before it has been assigned a value), introduce new errors and has very little chance on succes in medium to large programs.

The best method is to use static code analys tools (like QA/C or PCLint). Using compiler at high warning sensitivity level is a free option, with much less coverage as the specialized tools.

If you perform code reviews, you can also include a check for uninitialized variables on the checklist. This is no guarantee, but it will trigger manual checks from reviewers.

If it is runtime checking you want, then you can start of by intializing variables to an out-of-range value. For instance -1 for an otherwise postive value. Then you can check for

#define UNASSIGNED_VALUE -1
    static int number_of_apples = UNASSIGNED_VALUE;
    if (UNASSIGNED_VALUE == number_of_apples)
    {
       // error handling
    }

this is not a true 'unintialized' variable, but at least you can detect whether runtime assignments in legal range were done.

Adriaan
A: 

Checking whether or not a variable you're using is initialized (assigned) at runtime is notoriously difficult for C. There's no language support for it, and the information available at runtime simply is insufficient for perfect detection of uninitialized values. Dynamic analysis tools such as Valgrind/Memcheck goes through great lengths (such as keeping track of every byte of memory in your process's address space and then examining every store to mark a byte as intiialized ) to determine whether or not the value using is initialized and are still susceptible to false positives.

If you're just trying to minimize such errors in your programs, static analysis tools such as lint can do a reasonably good job of informing you of whether or not you're using uninitialized variables. In fact, I believe most compilers will do their best to tell you when you're doing this (though, they're certainly not perfect.)

Falaina
+1  A: 

As others have noted, you can't write a C program that detects if one of its own variables is uninitialized, and you should strive to make sure that variables are always initialized.

  • If your goal is to make sure all variables are initialized, a tool like valgrind can detect uses of uninitialized variables dynamically, through expensive run-time analysis.

  • If your goal is to make sure that private data is initialized exactly once, the usual method is to protect it with

    int i; static bool initialized = 0;

    ... if (!initialized) { initialized = 1; i = ... i's initial value ...; }

Norman Ramsey