1

#include <iostream>
using namespace std;

int main() {
int t;
cin>>t;
while(t--){
int n;
cin>>n;
int arr[n];
int count=0;
for(int i=0;i<n;i++){
cin>>arr[i];
count^=arr[i];
}
cout<<count<<endl;
}
return 0;
}

In the above program,
how does this code snippet work?
count^=arr[i];

Comments
  • 3
    That's the bitwise XOR assignment operator. It XORs left and right operands' bits and then assigns the result to left operand.
  • 8
    Btw, naming a hash "count" is punishable by ten years in the Cobol mines...
  • 3
    @Oktokolo I was confused by this and assumed that the question of OP is exactly about why this results in counting. 😄
  • 1
    I think CPP should be banned -.-
    I just can’t get around this syntax.
    #unpopularopinion
  • 2
    Should not compile

    `int arr[n];` is using a variable in a type definition, compiler will refuse. Replace by a dyn alloc: `int * arr = new int[n];`

    The domain main action is `count ^= arr[i];` bitwise arithmetic.

    `t` is the number or runs (in the domain, I don't know).

    `n` is the size of the user input for the current run.

    It takes n numbers from the user. It bitwise it togheter, and gives the result.

    I think `^` is the operator for XOR. So the result is a big XOR of all inputs in the array.
  • 3
    @Sandburg Nah, it's fine. GCC supports allocation of variable length arrays with a size known at runtime in C++ with an extension. The same "feature" is supported in C in standard version C99 and from C11 onwards...
  • 1
    @Oktokolo

    Sheesh! bro my bad
  • 2
    @dder Actually, it has been banned trice. But due to undefined behaviour in obscure edge cases, it always managed to somehow get back in...
Add Comment