I’m writing an application in C for my university course. In a section of my application I increase an integer iteratively. Using a printf statement I can tell that int1 is increase to 20 as it should be but then the run fails. I would like to know why this is the case?
int main() {
int i,int1=0, int2=0;
for (i = 0; i<10; i++) {
int1 = (int2 + 2);
int2 = int1;
}
}
The program has to by inline with ANSI C which I believe states that using:
int1 = (int2 + 2);
is undefined behaviour as the compiler cannot guarantee which of the ‘same’ variables is processed first. (Please do correct me if I am wrong however!) That is why I have taken the longer way around, but the application fails just the same using either way.
What is the reason this fails?
Your program doesn’t fail, you simply forgot to
return 0;at the end of your program, to indicate that your program ran correctly.As for the “undefined behavior”: No, that is perfectly valid C code.