Length is suppose to return how far along the counter went when going trough the string. However, it only returns the correct value when it is printed beforehand. If i comment out the printf it returns 0.
Does anyone have an explanation for this?
#include<stdio.h>
#include<string.h>
#define MAX 100
int length(char *s) {
int i;
for (i = 0; s[i] != '\0'; ++i)
printf("%d ", i); //<-- here
return i;
}
int main()
{
char s[MAX];
fgets(s, (char)sizeof(s), stdin);
s[strcspn(s, "\n")]='\0';
printf("Length: %d\n", length(s));
return 0;
}