0
#include <iostream>
using namespace std;
int main()
{
    int x[45]={5,3}, y=1, z=1;
    int i=45;
    while (x[--i])
    {
        
        cout<<"inside"<<endl;
    }
    cout<<i<<endl;
}

All it does is skipping the cycle, reducing i by 1 and ending the script. Like why does it never gets inside the cycle? Shouldn't it repeat the cycle 45 times until i is zero? I've got no clue.

  • 1
    Elements of array `x` with indices from `2` to `44` are initialized to `0`. The first iteration of the `while` loop checks if `x[44] != 0`, which is false. – paolo Jul 19 '22 at 14:20
  • Did you try using your debugger to inspect all the values in the array, and run this program, one line at a time, and see exactly what's happening? If not, why not? If you did, what did your debugger show you? – Sam Varshavchik Jul 19 '22 at 14:21
  • Time to use a debugger! – Jason Jul 19 '22 at 14:21
  • You're comparing `x[i]` to 0 while from your description it seems like you want to compare `i` to 0. – interjay Jul 19 '22 at 14:21
  • From [here](https://stackoverflow.com/a/20576217/12002570): *"When initialized with a list smaller than the array, only the specified elements are initialized as you expected; the rest are initialized to 0."* – Jason Jul 19 '22 at 14:25

2 Answers2

0

Not explicitly initialized elements of arrays of int some of whose elements are initialized are initialized to zero.

At first, x[--i] is evaluated to x[44]. The value of the element is zero, so it is interpreted as false and the loop body is not executed.

MikeCAT
  • 73,922
  • 11
  • 45
  • 70
0

At line

    while (x[--i])

The value inside while() isn't i but whatever is stored at the i'th index of array x. SInce yoz only initialized array x for x[0] and x[1] your compiler likely initialiazes all unitialized values to 0. The first value in while () is x[44], which is equal to 0, which is why the condition fails.

tempdev nova
  • 211
  • 1
  • 8