Hello friends,
I need one confirmation.
Please look at the following code:
Code:
#include <stdio.h>
#include <stdlib.h>
void sort (int[], int);
int main ( void )
{
int i;
int array[10];
for (i = 0; i < 10; i++)
{
array[i] = rand() % 100;
printf("%d ", array[i]);
}
putchar('\n');
sort (array, 10);
for (i = 0; i < 10; i++)
{
printf("%d ", array[i]);
}
return 0;
}
void sort (int array[], int len)
{
int i, j, save_var;
for (i = 1; i < len; i++)
{
save_var = array[i];
j = i - 1;
while (j >= 0 && array[j] > save_var)
{
array[j + 1] = array[j];
j --;
}
array[j + 1] = save_var;
}
}
please look at the sort function. At some point in program execution "j" will
become -1. In that case condition in while loop is false. However, since
in condition there is logical AND with other condition array[j] >save_var, at this
point this will become array[-1], and of course it would cause crash of the program.
I think that this doesn't matter because in C AND is short circuited and therefore
since j is -1 and j >= 0 is false, other part of condition will not be evaluated
and everything will work fine.
Am I right here?
Thanks