Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

arguments are reversed for a C function

I have a function that multiply two matrices A and B then prints the result. I got two different outputs when running the program in two similar ways.

first:

    FILE *f;
    f = fopen("in.txt","r");
    struct Mat* A = read_mat(f);
    struct Mat* B = read_mat(f);
    print_mat(mat_mul_1(A, B));

the output was the exact multiplication of

A * B

second:

    FILE *f;
    f = fopen("in.txt","r");
    print_mat(mat_mul_1(read_mat(f), read_mat(f)));

the output was the exact multiplication of

B * A

I want to know why the arguments has been reversed ?!

(as the 'mat_mul_1' function is a black box)

like image 259
M.ElSaka Avatar asked Nov 09 '11 07:11

M.ElSaka


2 Answers

Did you expect that the first read_mat(f) would be evaluated first?

C offers no such guarantees. The compiler is free to emit code that evaluates the arguments in any order it chooses.

The order of evaluation of the function designator, the actual arguments, and subexpressions within the actual arguments is unspecified, but there is a sequence point before the actual call.

like image 93
Mark Byers Avatar answered Oct 13 '22 11:10

Mark Byers


The reason why is as others have already pointed out, the order of evaluation of function parameters is unspecified behavior, and therefore should not be relied upon. But there is another, possibly severe issue here:

The function read_mat could be accessing static resources, such as static/global variables, and then return their values. Like this:

static int x;

int inc (void)
{
  x++;
  return x;
}

printf("%d %d", inc(), inc());

The actual result of the function will vary depending on the order of evaluation.

(This snippet is taken from an interview test I use when hiring C programmers. I ask what the output of this code is, and the correct answer is "2 1" or "1 2". The question tests whether the C programmer knows of the concepts static initialization and order of evaluation.)

like image 32
Lundin Avatar answered Oct 13 '22 11:10

Lundin