Reputation: 2464
I have been trying to understand of this following C-program:
#include <stdio.h>
int arr[] = {1,2,3,4};
int count;
int incr(){
return ++count;
}
int main(){
arr[count++]=incr();
printf("%d %d",count,arr[count]);
return 0;
}
The program gives 1 2 as output,what I am not gtting is why the value of count is 1 here and not 2 (since there are two increments)?
Upvotes: 1
Views: 329
Reputation: 506985
incr()
will return either 1
or 2
. It depends on whether the implementation first increments count
and then calls incr()
, or whether it first calls incr()
and then increments count
.
Please note that this choice does not mean that behavior is undefined. Since before a function is entered, and after a function is left, there is a sequence point at each point, both increments we have here are separated by a sequence point, so that the increment in main
, if it started to happen before the call, will be finished once entering incr()
, and if it happens after incr()
was called, will not have yet started until incr()
has left.
We have multiple scenarios here:
count++
, then call incr()
. This will write 2
into arr[0]
. incr()
, then do the increment for count++
. This will write 1
into arr[1]
.So, count
is always 2
, and arr[count]
is always 3
(it wasn't overwritten). So it should output 2 3
, not 1 2
.
I think that if you do the following, you have more options
int main(){
arr[++count]=incr();
printf("%d %d",count,arr[count]);
return 0;
}
Now, the value read from ++count
can be different than count+1
, because there is nothing that stops incr()
to be called after incrementing count
but before reading it. In this case we have
++count
, then call incr()
, then read from count
. This will write 2
into arr[2]
. ++count
, then read from count
, and then call incr()
. This will write 2
into arr[1]
.incr()
, then do the increment for ++count
and read from it. This will write 1
into arr[2]
.In this case, you can either have output 2 2
or 2 1
or 2 3
.
Upvotes: 4
Reputation: 92864
The order of evaluation of operands of =
operator is unspecified in arr[count++]=incr();
and since both the operands are trying to modify the same global variable count
the result would be different on different compilers depending upon the order of evaluation.
EDIT
Actually the behavior is undefined (which means anything can happen) because "the prior value of the variable count
is not accessed (only) to determine the value to be stored."
Upvotes: 5