Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

goto statements and alternatives in C

Tags:

c

goto

The program below is supposed to find the first all-zero row, if any, of an n × n matrix. Is this a correct approach to the problem, and is there another good structured approach to this code in C, or in any language in general? I'm trying to learn more about goto statements and appropriate uses/ alternatives to them. I appreciate any help!

int first_zero_row = -1; /* none */
int i, j;
for (i = 0; i < n; i++) {
    for (j = 0; j < n; j++) {
        if (A[i][j]) goto next;
    }
    first_zero_row = i;
    break;
    next: ;
}
like image 720
Joe Crawley Avatar asked Feb 18 '23 07:02

Joe Crawley


2 Answers

I'm not against using goto in some situations, but I think this can be re-written like this:

for (i = 0; i < n; i++) {
    for (j = 0; j < n; j++) {
        if (A[i][j]) break;
    }
    if (j==n) { /* the row was all zeros */
        first_zero_row = i;
        break;
    }
}
like image 139
iabdalkader Avatar answered Feb 26 '23 16:02

iabdalkader


What about using a little helper function to simplify the code in the loop:

bool is_zero_row(int* Row, int size)
{
    int j;

    for (j = 0; j < size; j++)
        if (Row[j] != 0)
            return false;

    return true;
}

and then

int first_zero_row = -1; /* none */
int i;
for (i = 0; i < n; i++) {
    if (is_zero_row(A[i], n))
    {
        first_zero_row = i;
        break;
    }
}
like image 22
Bo Persson Avatar answered Feb 26 '23 18:02

Bo Persson