Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C - Check if Integer is assigned

People also ask

How do you check if an input is a number C?

The C library function int isdigit(int c) checks if the passed character is a decimal digit character.

How do I know if my value is uninitialized?

Use the typeof operator to check if a variable is defined or initialized, e.g. if (typeof a !== 'undefined') {} . If the the typeof operator doesn't return a string of "undefined" , then the variable is defined.

How do you check if a number is within a range?

If x is in range, then it must be greater than or equal to low, i.e., (x-low) >= 0. And must be smaller than or equal to high i.e., (high – x) <= 0. So if result of the multiplication is less than or equal to 0, then x is in range.


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.


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.


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.


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


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.


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