30

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");
}
1

12 Answers 12

24

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.

5
  • @Kenny: "unless i is declared" is actually what I wanted to say, as "i" is the variable we're talking about, thanks. Aug 4, 2009 at 9:38
  • 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
    Aug 4, 2009 at 9:48
  • @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). Aug 4, 2009 at 10:33
  • 1
    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
    Aug 4, 2009 at 18:05
  • @Neil: This is true, and it's a nice distinction between the two. Aug 5, 2009 at 7:53
8

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.

4

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.

4

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.

4

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 ...;
    }
    
3

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

1
  • 15
    Obviously, because you'd never have a variable that is set during runtime.
    – GManz
    Mar 9, 2013 at 21:51
1

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.

1

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.

1

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.

2
  • See this message for example: gcc.gnu.org/ml/gcc-help/2007-07/msg00097.html
    – Makis
    Aug 4, 2009 at 13:58
  • 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
    Aug 4, 2009 at 13:58
0

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.

0
0

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.)

-5

In C# I'd use:

Nullable<int> i = null; /* null assignment */

if (i == null) {
   printf("Integer is unassigned!\n");
} else {
   printf("Integer is assigned!\n");
}

Not sure if this'd translate to C, though.

2
  • You are using both c#, and c syntax!, this code is hybrid cuz c# doesn't have a method called printf, instead it is Console.Write Oct 18, 2013 at 2:36
  • The user asked about C, not C#
    – Thales P
    Apr 12, 2020 at 18:00

Your Answer

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