Your C program is not guaranteed to produce that result - in fact, it's not guaranteed to produce any result. You can certainly observe that on a specific C implementation and at specific build settings, but it's not a property of the program you're seeing; it's a property of how the implementation handles this specific undefined program.
It would be equally valid for your C program to crash on startup, for the compiler to reject it, or any of a number of other, more esoteric outcomes. One valid translation of your C program both discards the writes to c
(since they are never read), optimizes c
away (since it is neither written to nor read from after the previous optimization), and optimizes a
away entirely (since it is initialized with a constant, and never written to). That would reduce the program down to
#include <stdio.h>
int main() {
printf("%d\n", 67305985);
return 0;
}
I was able to produce several translations close to this, though none that are exactly this, in both clang and gcc. However the program is not guaranteed to do this, either: it's an undefined program, so there is no well-specified result.
Nothing in Rust stops you from writing under-defined programs outright. However, safe rust is intended to be free from undefined behaviours, and writing outside of the bounds of an array is an undefined behaviour, so it you can't do that in safe rust.
I just want it to print a
, is it possible?
The only value a
can legally have in a well-specified program would be 67305985
, since there are no writes to a
anywhere in your program. The compiler is, under normal circumstances, allowed to rely on that observation to do things like eliminate the variable. However, the out-of-bounds writes to b
mean that the program is no longer well-specified, so there is no single correct output. Your expectation - that the program output 5
- is as invalid as the expectation that it output 67305985
.