Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define integer (int); What's the default value?

Tags:

c

int

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]) { ... }
like image 273
Naim Ibrahim Avatar asked Dec 26 '10 05:12

Naim Ibrahim


People also ask

How do you define int value?

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.

What is default value of int in Python?

A number or string to be converted to integer object. Default argument is zero. Number format. Default value: 10.

What is a default value example?

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.


2 Answers

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.

like image 69
James McNellis Avatar answered Nov 09 '22 05:11

James McNellis


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) { ... }
like image 42
Jonathan Leffler Avatar answered Nov 09 '22 06:11

Jonathan Leffler