Un exemple parmis tant d'autres, en C, dans lequel l'utilisation du goto *peut* sembler adaptée:
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
|
int** mafonct(int n1,int n2)
{
int** temp;
int i;
int j;
temp=malloc(sizeof(int*)*n1);
if(temp==NULL)
goto Err1;
for(i=0;i<n1;i++)
{
temp[i]=malloc(sizeof(int)*n2);
if(temp[i]==NULL)
goto Err2;
}
return temp;
Err2:
for(j=0;j<i;j++)
free(temp[j]);
Err1:
free(temp);
return NULL;
}; |
Et, pourtant, un algorithme très légèrement différent permettra de s'en passer:
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
|
int** fonct2(int n1,int n2)
{
int errcode=0;
int i;
int j;
int** temp;
temp=malloc(sizeof(int*)*n1);
if(temp==NULL)
errcode=1;
else
{
while(errcode==0 && i<n1)
{
temp[i]=malloc(sizeof(int)*n2);
if(temp[i]==NULL)
errcode=2;
else
i++;
}
}
switch(errcode)
{
case 2:
for(j=0;j<i;j++)
free(temp[i]);
case 1:
free(temp);
temp=NULL;
break;
}
return temp;
} |
Les deux codes sont exactement équivalents: il alloue tous les deux la mémoire pour une matrice d'entier de n1 lignes et de n2 colones...