Search code examples
cprintfcurly-braces

Why is this code printing "123" instead just 3?


I've got some code here:

int n = 0;
for(n = 1;n<4;n++)
printf("%d",n);
return 0;

Why does it return '123' instead of just '3'?

I tried to Google for this issue, but I couldn't find anything useful.


Solution

  • After asking my question, I think I see what you are getting at.

    What you have with

        int n = 0;
        for(n = 1;n<4;n++)
            printf("%d",n);
        return 0;
    

    is functionally the same as

        int n = 0;
        for(n = 1;n<4;n++)
        {
            printf("%d",n);
        }
        return 0;
    

    Since the for loop expects a statement, either a block of statements enclosed in braces, or a single one terminated with a semicolon as you have in your example. If you wanted it to just print 3 and for whatever reason wanted to use a loop just in increment a number, you would want to provide it with an empty statement as such:

        int n = 0;
        for(n = 1;n<3;n++);
        printf("%d",n);
        return 0;
    

    or

        int n = 0;
        for(n = 1;n<3;n++){}
        printf("%d",n);
        return 0;
    

    Both of which will only print 3.

    Please note that because the variable n gets incremented and then checked, using your original bounds n < 4, the loop would end when n = 4 and thus 4 would be printed. I changed this in my last two examples. Also note the incorrect use of the term return, as some comments pointed out.