I'm just now picking up C, so I'm pretty terrible since I'm coming from basic Python. I'm trying to print the elements in an array using a for-loop, but it's not coming out the right way.
#include <stdio.h>
#include <math.h>
int main()
{
int array[]={0,1,2,3,4};
int i;
for (i=0;i<5;i++);
{
printf("%d",array[i]);
}
printf("\n");
}
My output is
134513952
I have no clue why it's printing this.
You have an extra semicolon.
for (i=0;i<5;i++);
^
|
here -----+
That semicolon means your for loop has an empty body, and you end up printing after the loop completes, equivalently:
printf("%d", array[5]);
Since that value is beyond the end of the array, you get undefined behaviour and some strange output.
Editorial note: You should look into a compiler that gives better warnings. Clang, for example, gives this warning, even with no special flags passed:
example.c:7:20: warning: for loop has empty body [-Wempty-body]
for (i=0;i<5;i++);
^
example.c:7:20: note: put the semicolon on a separate line to silence this
warning
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With