Daniel Näslund
Daniel Näslund

Reputation: 2410

Do the C compiler know when a statement operates on a file and thus has "observable behaviour"?

The C99 standard 5.1.2.3$2 says

Accessing a volatile object, modifying an object, modifying a file, or calling a function that does any of those operations are all side effects, 12) which are changes in the state of the execution environment. Evaluation of an expression in general includes both value computations and initiation of side effects. Value computation for an lvalue expression includes determining the identity of the designated object.

I guess that in a lot of cases the compiler can't inline and possibly eliminate the functions doing I/O since they live in a different translation unit. And the parameters to functions doing I/O are often pointers, further hindering the optimizer.

.

volatile int ready;

int message[100];
void foo (int i) {
   message[i/10] = 42;
   ready = 1;
}

How do a C compiler determine if a statement operates on a file? In a free-standing embedded environment I declare registers as volatile, thus hindering the compiler from optimizing calls away and swapping order of I/O calls.

Is that the only way to tell the compiler that we're doing I/O? Or do the C standard dictate that these N calls in the standard library do I/O and thus must receive special treatment? But then, what if someone created their own system call wrapper for say read?

Upvotes: 2

Views: 93

Answers (1)

Serge Ballesta
Serge Ballesta

Reputation: 148965

As C has no statement dedicated to IO, only function calls can modify files. So if the compiler sees no function call in a sequence of statements, it knows that this sequence has not modified any file.

If only functions from the standard library are called, and if the environment is hosted, the compiler could know what they do and use that to guess what will happen.

But what is really important, is that the compiler only needs to respect side effects. It is perfectly allowed when it does not know, to assume that a function call could involve side effects and act accordingly. It will not be a violation of the standard if no side effects are actually involved, it will just possibly lose a higher optimization.

Upvotes: 3

Related Questions