I am a CS student preparing for a test in Introduction to CS in C language. I am solving some tests from the past and in one of them there was this question:
Look at the code below and state if there any errors. If so, correct them. Also if the program have any input write it down.
The code that came with the question is this:
#include <stdio.h>
#ifdef SIZE
#define MAX_SIZE (2*(SIZE))
#endif
int main() {
int i;
int arr[MAX_SIZE + 1];
for (i = 0; i < sizeof(arr)/sizeof(int);) {
arr[i] = i++;
printf("%d ", arr[i-1]);
}
return 0;
}
So of course I noticed that it wouldn't compile because the preprocessor would just skip the define part and MAX_SIZE
would be undeclared variable.
Beside that there shouldn't be any other compiling errors, I did notice the arr[i] = i++
but that should work even if a bit unpredictably (in the test I will call it an error though), so to test my answer I copied it to my IDE and fixed it to my best of knowledge.
(I picked 5 randomly)
#include <stdio.h>
#define SIZE 5
#ifdef SIZE
#define MAX_SIZE (2*(SIZE))
#endif
int main()
{
int i;
int arr[MAX_SIZE + 1];
for (i = 0; i < sizeof(arr)/sizeof(int);)
{
arr[i] = i++;
printf("%d ", arr[i-1]);
}
return 0;
}
to my surprise the function went into an endless loop printing 8 all the time.
After some digging I figured out that for some reason when i
is equal to 10 it stops increasing. Some more digging made me realize that it's only happening when SIZE is an odd number and it won't happen if the ++
is prefix (as in ++i
).
If the changes mentioned above are applied, the output is as I expected, except that arr[0]
doesn't get assigned.
All of that made me conclude that it is a compiler optimization error of some kind, bit I really would like it if someone could explain to me what is really happening here.