开发者

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

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]) { ... }


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 an integer is declared globally then it is initialized automatically with zero but if it is local then contains garbage value until and unless itis given some value


If an integer is not initialized, its value is undefined as per C


Since you've included the ={0};, the entire array is filled with zeros. If this is defined outside any function, it would be initialized with zeros even without the initializer. if (!data[x]) is equivalent to if (data[x] == 0).


// File 'a.c'

   #include <stdio.h> 

   void main()
    {
            int i, j , k;
            printf("i = %i j = %i k = %i\n", i, j, k);
    }

// test results

> $ gcc a.c 
> $ ./a.out 
> i = 32767 j = 0 k = 0
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜