J.Doe
J.Doe

Reputation: 77

C - fprintf and printf inside loops don t print to screen

I just discovered that the function fprintf can be used to print something to the screen.

I have this minimal just below, however it doesn t output anything to the screen. Why?

#include <stdio.h>

int main(void)
{
    int i,j,k;

    for(i=0;i<4;i++)
    {
        for(j=0;j<0;j++)
        {
            for(k=0;k<3;k++)
            {
                printf("test\n");
                fprintf(stderr, "test\n");

            }
        }       
    }

    return 0;
}

I am running ubuntu 14.04 and compiling this code as follows: gcc main.c -o main

Upvotes: 1

Views: 182

Answers (3)

abhiarora
abhiarora

Reputation: 10460

I have this minimal just below, however it doesn t output anything to the screen. Why?

It wouldn't because control never reaches to the printf() statement. Because your middle for loop has a test condition which always fails which prevents even inner for loop to execute.

for(j=0;j<0;j++)
.
.

The condition j<0 when j is initialized with 0 will always evaluates to false. Fix the middle for loop and your problem will be solved.

You can debug your program using gdb. Learn few commands to work with gdb and you can see on your own where is the problem lies.

Upvotes: 0

Marc B
Marc B

Reputation: 360922

Why should it print anything? One of your loops has an impossible condition:

    for(j=0;j<0;j++)
              ^---

since j starts at 0, it can never be LESS than 0, so the loop immediately exits without ever executing the body.

Upvotes: 5

Michael Albers
Michael Albers

Reputation: 3779

Your second loop is wrong. j is initialized to zero and the conditional is j<0. With for loops the conditional is evaluated before the first iteration.

Upvotes: 2

Related Questions