Home > database >  using void function. is this code okay? it show no output
using void function. is this code okay? it show no output

Time:06-18

using void function. is this code okay? it shows no output

I am trying to create a void function in C programming that works with pointers. I have created the following functions:

 #include<stdio.h>
 void main()
 {
   int c;
   for(;c=0;)
   {
     printf("Hello");
   }
 }

CodePudding user response:

You have to modify the for loop, for(;c=0;) A for loop works like this, consider this example,for(x;y;z) for the first run, the compiler reads x (which is the initializer), and sees if it is compatible with y, if it is the loop is executed. After the loop has been executed, it executes z. for the rest of its loops, it would keep repeating as long as the variable's value is compatible with y. In your case, however, the condition for the loop (i.e y) is c=0, which is false, as c has not been given a value when it was initialized. The loop would run only if y is true, that is, c=0 is true. If you initialize the variable c with value 0, and change the condition to c<=0, the code would run infinite times.

CodePudding user response:

A for-loop has four parts,

for ( init-clause ; cond-expression ; iteration-expression ) loop-statement

In your loop, you have an empty init-clause and an empty iteration-expression. You have a cond-expression which contains the predicate that needs to be true for the loop to execute the loop-statement.

Your cond-expression contains an assignment, c=0, and in boolean contexts, the value of c will be implicitly converted to true if it's not 0 and false if it is 0, which it is, so the loop-statement will never be executed.

I suggest that you move the assignment to the init-clause and make proper use of the cond-expression and iteration-expression:

#include<stdio.h>

int main()        // make it int to be portable
{
    int c;
    for(c=0; c < 10;   c)  // Loop 10 times
    {
        printf("Hello\n"); // \n added to get each Hello on a separate line
    }
}

If you don't need the value of c after the loop, move the declaration of c into the init-statement of the loop:

    // int c; // not needed
    for(int c=0; c < 10;   c)  // Loop 10 times
  • Related