int i;
int data[5] = {0};
data[0] = i;
What's the value in data[0]?
Also, what's the meaning of this line?
if (!data[0]) { ... }
An integer (pronounced IN-tuh-jer) is a whole number (not a fractional number) that can be positive, negative, or zero. Examples of integers are: -5, 1, 5, 8, 97, and 3,043. Examples of numbers that are not integers are: -1.43, 1 3/4, 3.14, . 09, and 5,643.1.
A number or string to be converted to integer object. Default argument is zero. Number format. Default value: 10.
For instance, if a bank's interest rate for the current financial year is 8 percent, this may be set as the default value. This relieves the user from having to enter it repeatedly into the database.
In most cases, there is no "default" value for an int
object.
If you declare int i;
as a (non-static) local variable inside of a function, it has an indeterminate value. It is uninitialized and you can't use it until you write a valid value to it.
It's a good habit to get into to explicitly initialize any object when you declare it.
It depends on where the code is written. Consider:
int i;
int data[5] = {0};
void func1(void)
{
data[0] = i;
}
void func2(void)
{
int i;
int data[5] = {0};
data[0] = i;
...
}
The value assigned to data[0]
in func1()
is completely deterministic; it must be zero (assuming no other assignments have interfered with the values of the global variables i
and data
).
By contrast, the value set in func2()
is completely indeterminate; you cannot reliably state what value will be assigned to data[0]
because no value has been reliably assigned to i
in the function. It will likely be a value that was on the stack from some previous function call, but that depends on both the compiler and the program and is not even 'implementation defined'; it is pure undefined behaviour.
You also ask "What is the meaning of this?"
if (!data[0]) { ... }
The '!
' operator does a logical inversion of the value it is applied to: it maps zero to one, and maps any non-zero value to zero. The overall condition evaluates to true if the expression evaluates to a non-zero value. So, if data[0]
is 0, !data[0]
maps to 1 and the code in the block is executed; if data[0]
is not 0, !data[0]
maps to 0 and the code in the block is not executed.
It is a commonly used idiom because it is more succinct than the alternative:
if (data[0] == 0) { ... }
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