-6

I'm beginner in C programming (just started) and i need help from you to understand the output of this very simple code:

int main()
{
   int x=1;
   for (;x<=10;x++);
   printf("%d\n",x);
    return 0;
}

output is: 11

the same output if x value is <=11 and if x value is 12 or more, it prints the exact value of x (ex: if int x=12; the output is 12).

how did the computer understand this code?

karam
  • 1
  • 1
    Possible duplicate of [What is the full "for" loop syntax in C (and others in case they are compatible)?](http://stackoverflow.com/questions/276512/what-is-the-full-for-loop-syntax-in-c-and-others-in-case-they-are-compatible) – Michael Albers Nov 01 '16 at 03:50
  • 2
    "how did the computer understand this code?" - He might have read a C book ... How about following its example? – too honest for this site Nov 01 '16 at 03:54
  • 1
    my 2 cents... This is rarely how loops are used. The `for` loop doesn't do anything except increment `x` because of it's trailing semicolon `;`. Usually you want to wrap the body of a loop in `{...}` and actually do something in the body based on the loop control variable (`x` in this case). All this loop effectively does is insert a (quite small) time delay. In fact compiler optimizations would probably just omit the loop entirely and set `x` to 11. – yano Nov 01 '16 at 04:07
  • @MichaelAlbers How is that a duplicate? The question you linked is about understanding obfuscated code. While this question is about asking how utterly fundamental things work. – Lundin Nov 01 '16 at 07:27

2 Answers2

3

So,

int main()
{
   int x=1;           // line 1
   for (;x<=10;x++);  // line 2
   printf("%d\n",x);  // line 3
   return 0;          // line 4
}

Line 1 initializes x to 1.

Line 2 keeps increasing x by 1 until it reaches 11. The first semicolon indicates "don't do anything before starting the loop", x<=10 indicates keep going until x > 10 (so when x = 11) and x++ means increase x by 1 each time. If x >= 11, this line gets basically skipped because x is already greater than 10.

Line 3 prints out x to the command line (in this case, x = 11 if x started out less than 11 or just x if x started at >= 11 due to the previous line)

Line 4 means the program was successful, exit the program.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Dec Sander
  • 1,327
  • 1
  • 9
  • 5
0

for is this:

for(*init-expr*; *test-expr*; *update-expr*) *body-statement* Or rather, commonly, it can be decribed like this:

*init-expr*; while(*test-expr*){ *body-statement* *update-expr*; } and, your for statement is followed by a semicolon, where body-statement is.So, it is a "null statement", just loop and update x, when finishes the loop, just print the x after loop, so, the output is 11.