Is there a way to check if a variable has been initialized or not in C?
Consider the following example,
int main(){ int a = 3, b = 7, c; if ( a > b ) c = a-b; // Now, how can I check if the variable "c" has some value or not // I don't want check like this, // if ( isalpha(c) ) or if ( isdigit(c) ) // or anything similar to like that }
In other words, does C has some function like defined
in Perl
. In Perl
, I can simply do if (defined c)
that would check if the variable is defined or not, and it'd return False for above example. How can I achieve the same in C?
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.
The definition of a variable in C is not checked by code writer. The compilers do it for you. When compile and link your C code, the compiler will check all variable's definitions. An error will be invoked and the compiling or linking process will stop if there are undefined variables found in your code.
There is no way in the C++ language to check whether a variable is initialized or not (although class types with constructors will be initialized automatically). Instead, what you need to do is provide constructor(s) that initialize your class to a valid state.
Unlike some programming languages, C/C++ does not initialize most variables to a given value (such as zero) automatically. Thus when a variable is assigned a memory location by the compiler, the default value of that variable is whatever (garbage) value happens to already be in that memory location!
C does not have this ability. You have two main options:
For example, if you know that the value of c
will never be negative, then initialize it to -1
, and test that for that.
Create another variable bool we_set_c_to_something = false;
and then set it to true
when you write to c
.
C is a compiled language which doesn't support runtime variable binding, while Perl is a interpreted language which support dynamic typing. So you can check the definition of a variable in Perl, but not in C.
When you declare a variable in C int c;
, this variable c
is defined but without initialization. The declaration and definition are in one statement.
The definition of a variable in C is not checked by code writer. The compilers do it for you. When compile and link your C code, the compiler will check all variable's definitions. An error will be invoked and the compiling or linking process will stop if there are undefined variables found in your code.
Hope this will make you distinguish the differences.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With