how to initialize the “min” variable properly?

后端 未结 4 441
野性不改
野性不改 2021-01-29 10:17

I have a small problem in my code for finding the minimum value from a series of numbers. When I initialize min = 0, the minimum value turns out as 0. But when I do

4条回答
  •  [愿得一人]
    2021-01-29 10:38

    The compiler warning is because accessing the value of uninitialised variables gives undefined behaviour.

    A common technique to find a minimum value in an array is to initialise the min to be the first element in the array, then iterate over subsequent elements

     min = a[0];
     for (i = 1; i < 20; ++i)     /* assume 20 elements */
         if (a[i] < min) min = a[i];
    

    This works for all numeric types that can be compared using the < operator, without having to muck around trying to find a value that exceeds all possible values in the array.

    The other thing to watch is that array indexing starts at zero. So an array with 20 elements (as in int a[20]) has valid indices 0 to 19. Running a loop from 1 to 20 - and therefore accessing a[1] through to a[20] gives undefined behaviour, since a[20] does not exist.

提交回复
热议问题