[Solved] What does this following C code implement [closed]


The code is probably intended to create an identity matrix with 1’s on the leading diagonal and 0’s elsewhere.

The Fortran equivalent of that code is used as the first example of bad code in the classic Elements of Programming Style by Kernighan and Plauger.

Working from memory, the Fortran code was roughly:

       DO 10 I = 1, N
          DO 10 J = 1, N
    10       A(I,J) = (I/J)*(J/I)

(There might have been two labels, 10 and 20 say, and one or two continue statements, but I think it was like that. At the time, columns 1-5 were reserved for numeric labels, column 6 was a continuation indicator, and the program occupied columns 7-72, with columns 73-80 being an optional statement sequence number.)


Since y is used but not declared, if it compiles, y must be an external variable (either a global variable or a variable with file scope: extern int y; or int y; or static int y; outside the function).

Since i and j are used but not declared, if it compiles, they too must be external variables. And given that neither i nor j is changed, the same value (either 0 or 1, depending on whether i != j) is in fact assigned to each element of a.

The more nearly ‘correct’ code implementing the same (bad) algorithm should be:

void h(int **a, int b)
{
    for (int x = 1; x <= b; x++)
        for (int y = 1; y <= b; y++)
            a[x-1][y-1] = (x/y)*(y/x);
}

Of course, this is not very C-like, but it does avoid divide-by-zero problems. However, cleaner and simpler code can be written:

void h(int **a, int b)
{
    for (int x = 0; x < b; x++)
    {
        for (int y = 0; y < b; y++)
            a[x][y] = 0;
        a[x][x] = 1;
    }
}

The function should be renamed to something more meaningful.

7

solved What does this following C code implement [closed]