It’s usually a good idea to explain what you understand, so we don’t have to treat you as though you know nothing. Important note: This code behaves erratically. I’ll discuss that later.
The exclusive or operator (^
) produces its result by applying the following pattern to the binary representation of the numbers in question:
- Where both operands (sides of the operator) contain different bits, the result will contain a
1
bit. For example, if the left hand side contains a right-most bit of 0 and the right hand side contains a right-most bit of 1, then the result will contain a right-most bit of 1. - Where both operands (sides of the operator) contain the same bit, the result will contain a 0.
So as an example, the operands of 15 ^ 1
have the following binary notation:
1111 ^
0001
… and the result of this exclusive or operation will be:
1110
Converted back to decimal, that’s 14. Xor it with 1 again and you’ll end up back at 15 (which is the property the silly xor swap takes advantage of).
The array[index]
operator obtains the element within array
at the position indicated by index
.
The ^=
operator is a compound operator. It combines the exclusive or and assignment operators. a ^= arr[i];
is roughly equivalent to a = a ^ arr[i];
. That means: Calculate the exclusive or of a
and arr[i]
, and assign it back into a
.
for (i = 0 ; i < N ; ++i) /*
* XXX: Insert statement or block of code
*/
This denotes a loop, which will start by assigning the value 0
to i
, will repeatedly execute the statement or block of code while i
is less than N
(100), incrementing i
each time.
In summary, this code produces the exclusive or of the first 100 elements of the array arr
. This is a form of crude checksum algorithm; the idea is to take a group of values and reduce them to a single value so that you can perform some form of integrity check on them later on, perhaps after they’ve been trasmited via the internet or an unreliable filesystem.
However, this code invokes undefined behaviour because it uses unspecified values. In order to avoid erratic behaviour such as unpredictable values or segfaults (or worse yet, situations like the heartbleed OpenSSL vulnerability) you need to make sure you give your variables values before you try to use those values.
The following declaration would explicitly initialise the first element to 42
, and implicitly initialise all of the others to 0
:
unsigned long arr[2*N + 1] = { 42 };
It is important to realise that the initialisation part of the declaration = { ... }
is necessary if you want any elements not explicitly initialised to be zeroed.
solved I need help understanding this code in C [closed]