I read and understood C executes a program sequentially, from top to bottom. So, for instance, this easy function:
int main(void)
{
int i;
i = -1;
while (++i < 5)
printf("%i\n", i);
printf("end\n");
return (0);
}
will return:
0
1
2
3
4
end
But, I had a couple of cases yet where this has not happened, and I'm not able to understand why... For instance here I would expect to have a "!" before each of the if/else result (so before "o" or "."), but all the "!" are printed at the end:
int g_lines = 12;
int g_columns = 34;
char g_vacio = '.';
char g_obstaculo = 'o';
char g_lleno = 'x';
void print_map(void)
{
int line;
int col;
line = 0;
while (line <= g_lines - 1)
{
col = 0;
while (col < g_columns)
{
printf("!");
if (col % 2 == 0)
write(1, &g_lleno, 1);
else
write(1, &g_vacio, 1);
col++;
}
write(1, "\n", 1);
line++;
}
}
Output:
x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.
x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.
x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.
x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.
x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.
x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.
x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.
x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.
x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.
x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.
x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.
x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
What's the reason why the "!" is printed just at the end?
I decided to exchange printf("!")
with ````write(1, "!", 1)`````and now, surprisingly, the result is how expected.
while (col < g_columns)
{
write(1, "!", 1);
if (col % 2 == 0)
write(1, &g_lleno, 1);
else
write(1, &g_vacio, 1);
col++;
}
now the output is:
!x!.!x!.!x!.!x!.!x!.!x!.!x!.!x!.!x!.!x!.!x!.!x!.!x!.!x!.!x!.!x!.!x!.
!x!.!x!.!x!.!x!.!x!.!x!.!x!.!x!.!x!.!x!.!x!.!x!.!x!.!x!.!x!.!x!.!x!.
!x!.!x!.!x!.!x!.!x!.!x!.!x!.!x!.!x!.!x!.!x!.!x!.!x!.!x!.!x!.!x!.!x!.
!x!.!x!.!x!.!x!.!x!.!x!.!x!.!x!.!x!.!x!.!x!.!x!.!x!.!x!.!x!.!x!.!x!.
!x!.!x!.!x!.!x!.!x!.!x!.!x!.!x!.!x!.!x!.!x!.!x!.!x!.!x!.!x!.!x!.!x!.
!x!.!x!.!x!.!x!.!x!.!x!.!x!.!x!.!x!.!x!.!x!.!x!.!x!.!x!.!x!.!x!.!x!.
!x!.!x!.!x!.!x!.!x!.!x!.!x!.!x!.!x!.!x!.!x!.!x!.!x!.!x!.!x!.!x!.!x!.
!x!.!x!.!x!.!x!.!x!.!x!.!x!.!x!.!x!.!x!.!x!.!x!.!x!.!x!.!x!.!x!.!x!.
!x!.!x!.!x!.!x!.!x!.!x!.!x!.!x!.!x!.!x!.!x!.!x!.!x!.!x!.!x!.!x!.!x!.
!x!.!x!.!x!.!x!.!x!.!x!.!x!.!x!.!x!.!x!.!x!.!x!.!x!.!x!.!x!.!x!.!x!.
!x!.!x!.!x!.!x!.!x!.!x!.!x!.!x!.!x!.!x!.!x!.!x!.!x!.!x!.!x!.!x!.!x!.
!x!.!x!.!x!.!x!.!x!.!x!.!x!.!x!.!x!.!x!.!x!.!x!.!x!.!x!.!x!.!x!.!x!.
Can anybody explain why?