Search code examples
carraysinitializationcompound-assignment

Array elements (after using compound assignment operator) yields garbage value, why?


#include<stdio.h>
void main(void)
{
    int a[5]={90,78,77,98,98}, b[5]={80,45,67,88,57}, c[5]={88,99,65,55,74},total[3],i,j;
    for(j=0;j<=4;j++)
        {
            total[0]+=a[j];
            total[1]+=b[j];
            total[2]+=c[j];
        }

    for(i=1;i<=3;i++)
    {
    printf("%d행의 가로 합 : %d\n",i,total[i-1]);
    }
}

total[0] and total[1] are right value, but total[2] is wrong value. I cannot find my fault. Can you explain it?


Solution

  • The first problem here is in the code

            total[0]+=a[j];
            total[1]+=b[j];
            total[2]+=c[j];
    

    where you're using total[n]s un-initialized. They contain indeterminate values and using them invokes undefined behavior.

    To elaborate, total being an uninitialized automatic local variable, the initial values of the elements of the array are indeterminate. By using the += operator on those elements, you're trying to read (use) the values which are indeterminate, so it invokes UB in your case.

    Related quote from C11, chapter §6.5.16.2, Compound assignment,

    A compound assignment of the form E1 op= E2 is equivalent to the simple assignment expression E1 = E1 op (E2), except that the lvalue E1 is evaluated only once, and with respect to an indeterminately-sequenced function call, the operation of a compound assignment is a single evaluation. If E1 has an atomic type, compound assignment is a read-modify-write operation with memory_order_seq_cst memory order semantics.

    So, by using the += on an uniniitilized value, _you're trying to read (or use) a variable with indeterminate value, which causes the UB.

    If you want, you can initialize the whole array by using a syntax like

      int total[3] = {0};
    

    which initializes all elements of the array to 0, which is what basically you were expecting.

    That said, void main(void) is not a conforming signature for main() in a hosted environment, as per the spec, it should be int main(void), at least.