Home > database >  incorrect data in array index - what will happen?
incorrect data in array index - what will happen?

Time:11-17

I found a mistake I made in my code associated with indexing an array. It compiled and I didn't notice the issue for some time. I'm curious what the index really was.

Intended code:

if(arr[i] > 3){//do stuff}

what was written:

if(arr[i > 3]){//do stuff}

what did the array index end up being?

CodePudding user response:

In reality, what happens is very simple.

In the first case, the if checks each element of the array and sees if it is greater than 3.

In the second case, it's more complex than it seems. In practice, as long as the i is greater than 3, the index taken will be 1, as it satisfies the equation x > 3, otherwise I take the index 0.

In practice it is the transformation of the boolean value into an integer value. Once it takes the index, the if does nothing but be true if the value is non-zero, otherwise if the value inside the array is 0 it will be false.

A very practical example for the second problem would be:

int arr[4] = {1,2,3,4};
cout << arr[2 > 4] << endl; //The output would be 1, since 2 > 4 would be false and would return 0 as a result.

Sorry if I made a bad explanation but I tried my best :)

  • Related