Search code examples
carrayspre-increment

Strange behavior from a simple C program


If I run the following code, graph[0][0] gets 1 while graph[0][1] gets 4.

In other words, the line graph[0][++graph[0][0]] = 4; puts 1 into graph[0][0] and 4 into graph[0][1].

I would really appreciate if anyone can offer reasonable explanation.

I observed this from Visual C++ 2015 as well as an Android C compiler (CppDriod).

static int graph[10][10];
void main(void)
{
    graph[0][++graph[0][0]] = 4;
}

Solution

  • Let's break it down:

    ++graph[0][0]
    

    This pre-increments the value at graph[0][0], which means that now graph[0][0] = 1, and then the value of the expression is 1 (because that is the final value of graph[0][0]).

    Then,

    graph[0][/*previous expression = 1*/] = 4;
    

    So basically, graph[0][1] = 4;

    That's it! Now graph[0][0] = 1 and graph[0][1] = 4.