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
When I initialize
min = 0
, the minimum value turns out as0
.
because in that case, if (min > a[i])
is always false. Remeber, a[i]
is > = 100.
But when I don't initialize
min
, the answer is correct!
if you don't initalize the local variable, it's value in indeterminent and contains some garbage value (possibly a large one). So, seemingly, your logic works and you're apparently getting the right answer. However, using values of uninitalized local variable invokes undefined behaviour.
Solution:
Initialize min
with the largest possbile value, INT_MAX
present in header file.
If you don't initialize a local variable, its value is indeterminate, and using that will lead to undefined behavior.
What you should do is initialize it to a large value, just like you initialize max
to a small value. Use INT_MAX
from the <limits.h> header file.
Also, if your variables can't be negative, you should probably use unsigned int
, and initialize min
to UINT_MAX
.
You must initialize min
with a large number, otherwise 0
might remain as the smallest number.
You can initialize min
as
int min = INT_MAX;
INT_MAX
is the largest value that can be held by an int
( Must add <limits.h>
for INT_MAX
).
If you don't initialize min
with a value, then it will have an indeterminate value, which can be anything, so always initialize your local variables before using their values..
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.