Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Don't understand the output of this C program

Tags:

c

Here's the code:

#include <stdio.h>

int main (void)
{
    int value[10];
    int index;

    value[0] = 197;
    value[2] = -100;
    value[5] = 350;
    value[3] = value[0] + value[5];
    value[9] = value[5] / 10;
    --value[2];

    for(index = 0; index < 10; ++index)
        printf("value[%i] = %i\n", index, value[index]);
    return 0;
}

Here's the output when compile:

value[0] = 197
value[1] = 0
value[2] = -101
value[3] = 547
value[4] = 0
value[5] = 350
value[6] = 0
value[7] = 0
value[8] = 1784505816
value[9] = 35

I don't understand why value[8] returns 1784505816? Isn't value[8] supposed be = value[6] = value[7] = 0? By the way, I compile the code via gcc under Mac OS X Lion.

like image 649
William Li Avatar asked Sep 22 '11 07:09

William Li


People also ask

How can I predict the output of below program?

Predict the output of below programs. Output:Above program goes in infinite loop because n is never zero when loop condition (n != 0) is checked. Output is dependent on the compiler. For 32 bit compiler it would be fffffffe and for 16 bit it would be fffe.

Which type of output is dependent on the compiler?

Output is dependent on the compiler. For 32 bit compiler it would be fffffffe and for 16 bit it would be fffe. Explanation: After pre-processing phase of compilation, printf statement will become.

What happens to control after continue statement in C++?

So after continue statement, control transfers to the statement while (false). Since the condition is false ‘i’ is printed only once. Now try below program. The above program works because string constants are stored in Data Section (not in Stack Section).

How will printf statement predict the output of below program?

Predict the output of below programs. Output:Above program goes in infinite loop because n is never zero when loop condition (n != 0) is checked. Output is dependent on the compiler. For 32 bit compiler it would be fffffffe and for 16 bit it would be fffe. Explanation: After pre-processing phase of compilation, printf statement will become.


2 Answers

value[8] was never initialized, therefore its contents are undefined and can be anything.

Same applies to value[1], value[4], value[6], and value[7]. But they just happened to be zero.

like image 77
Mysticial Avatar answered Oct 24 '22 03:10

Mysticial


Objects with automatic storage duration declared without an initializer have indeterminate values until they are assigned to. Technically, it causes undefined behavior to use the value (e.g. printing int) of an object which has an indeterminate value.

If you want the array to be initialized to zero you need to provide an initializer. E.g.

int value[10] = {0};
like image 43
CB Bailey Avatar answered Oct 24 '22 01:10

CB Bailey