18
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]) { ... }
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Naim Ibrahim
  • 266
  • 1
  • 2
  • 10

7 Answers7

28

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.

James McNellis
  • 348,265
  • 75
  • 913
  • 977
  • @James McNellis, You meant "`int` type", not `int` object, right? :) – Jacob Relkin Dec 26 '10 at 05:44
  • 4
    @Jacob: Types don't have values. Objects have values. An object that is not explicitly initialized might have some default value in some languages (or even in C, in certain circumstances). – James McNellis Dec 26 '10 at 05:46
  • @James McNellis Do you mind explaining then why this program outputs 5 zeroes? `int x[5];for(int i = 0; i < 5; i++) {printf("%d", x[i]);}` – Jacob Relkin Dec 26 '10 at 05:46
  • @James McNellis I've never really heard the term "object" in the context of C variables. They're not strictly objects, are they? – Jacob Relkin Dec 26 '10 at 05:47
  • 4
    @Jacob: Because that's the result you happened to get when you compiled the program with your compiler with certain settings at a particular time. When I compile and run that program, I get an output of `-858993460-858993460-858993460-858993460-858993460`. It's likely that your compiler is zero-initializing memory for you. Mine, Visual C++ with standard debug build settings, is pre-initializing uninitialized objects with `0xcc` so that they are more easily detected. – James McNellis Dec 26 '10 at 05:48
  • 1
    @Jacob You got lucky, or your compiler implements a default value of zero. But the ANSI C spec does not specify a default value for non-static data members. And I've never seen a compiler spec define it that way either. – boiler96 Dec 26 '10 at 05:49
  • 5
    @Jacob: An "object" in both C and C++ is just "a region of storage." It's a sequence of bytes that represent something. – James McNellis Dec 26 '10 at 05:50
  • @James McNellis Thanks for the info, I've always used the term "object" when referring to instances of a class... – Jacob Relkin Dec 26 '10 at 05:51
  • +1 for no default value, it could be a "random" number in the storage location - I got data[0] equals to 232111 one time an 51 on second try under linux – user44298 Dec 26 '10 at 06:31
  • Note--a good habit in one language isn't a good habit in every language. Java can help you quite a bit if you do not initialize variables to meaningless values (0, null...). – Bill K Dec 26 '10 at 07:41
9

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) { ... }
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
  • 1
    I really don't get why you say the value being assigned to data[0] in func1 is fully deterministic.. it seems 100% indeterminate as long as i has not been initialized – Jules G.M. Jun 30 '14 at 21:19
  • 1
    @Julius: In the context of `func1()`, `i` is a global variable and global (`int`) variables are initialized to 0 unless there is some other initializer specified. (The story is slightly more complex for some other types, but all global variables are initialized, either to a specified value or to 'zero'.) Now, if some other code has modified the value of `i`, then the value assigned to `data[0]` will not necessarily be 0, but the value is still defined and not indeterminate. – Jonathan Leffler Jun 30 '14 at 21:25
5

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

mukesh
  • 111
  • 2
  • 1
4

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

JRK
  • 182
  • 9
3

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).

Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111
  • 2
    `data[0]` is subsequently set to `i`. The OP boils down to asking about what the value of `i` is, since it hasn't been assigned one. – cHao Dec 26 '10 at 05:55
1

// 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
Kevin Meredith
  • 41,036
  • 63
  • 209
  • 384
0

As @James McNellis stated in 2010, the standards for programming languages leave the initial value of a variable to the compiler implementation, and results differ from one compiler implementation to another.

I came here to review the state of affairs in this regard because I remembered observing that some compilers initialize arrays of integers to zero.

After reading the inconclusive answers recorded here, I constructed a small static method in the assembly that I use to conduct such experiments before I implement a technique in production code. My current project requires porting some JavaScript code to C#. Since the JavaScript interpreter doesn't initialize anything, that implementation opened with a FOR loop to initialize a large array of integers. Before I blindly left it in the C# implementation.

The method follows.

        private static void IntegerArrayGym ( )
    {
        int [ ] ints = new int [ 10 ];

        Console.WriteLine ( $"{TEST_INTEGER_ARRAY_GYM} Begin:{Environment.NewLine}" );

        int intArrayLength = ints.Length;

        Console.WriteLine ( $"    The test array consists of {ints} uninitialized integers.{Environment.NewLine}" );

        for ( int intJ = ArrayInfo.ARRAY_FIRST_ELEMENT;
                  intJ < intArrayLength;
                  intJ++ )
        {
            Console.WriteLine ( $"    Value of integer at ordinal position {ArrayInfo.OrdinalFromIndex ( intJ )} = {ints [ intJ ]}" );
        }   // for ( int intJ = ArrayInfo.ARRAY_FIRST_ELEMENT; intJ < intArrayLength; intJ++ )

        Console.WriteLine ( $"{Environment.NewLine}{TEST_INTEGER_ARRAY_GYM} Done!" );
    }   // private static void IntegerArrayGym

The output follows.

CSharp_Lab, version 7.92.170.0 Begin @ 03/06/2023 22:58:49.124 (03/07/2023 04:58:49.124 UTC)

IntegerArrayGym Begin:

The test array consists of System.Int32[] uninitialized integers.

Value of integer at ordinal position 1 = 0
Value of integer at ordinal position 2 = 0
Value of integer at ordinal position 3 = 0
Value of integer at ordinal position 4 = 0
Value of integer at ordinal position 5 = 0
Value of integer at ordinal position 6 = 0
Value of integer at ordinal position 7 = 0
Value of integer at ordinal position 8 = 0
Value of integer at ordinal position 9 = 0
Value of integer at ordinal position 10 = 0

IntegerArrayGym Done! Please press the ENTER (Return) key to exit the program.

David A. Gray
  • 1,039
  • 12
  • 19