Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
}
like image 376
InKwon Park Avatar asked Jun 08 '26 07:06

InKwon Park


2 Answers

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.

like image 200
Jashaszun Avatar answered Jun 10 '26 03:06

Jashaszun


First let's see what is the unary (prefix) increment operator does.

The value of the operand of the prefix ++ operator is incremented. The result is the new value of the operand after incrementation.

So, in case of

graph[0][++graph[0][0]] = 4;

first, the value of graph[0][0] is incremented by 1, and then the value is used in indexing.

Now, graph being a static global variable, due to implicit initialization, all the members in the array are initialized to 0 by default. So, ++graph[0][0] increments the value of graph[0][0] to 1 and returns the value of 1.

Then, the simpllified version of the instrucion looks like

graph[0][1] = 4;

Thus, you get

  • graph[0][0] as 1
  • graph[0][1] as 4.

Also, FWIW, the recommended signature of main() is int main(void).

like image 33
Sourav Ghosh Avatar answered Jun 10 '26 02:06

Sourav Ghosh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!