Home > Blockchain >  C for loop: cond-expression expressed as an expression which is contextually convertible to bool?
C for loop: cond-expression expressed as an expression which is contextually convertible to bool?

Time:10-15

How C for loop having cond-expression expressed as an expression which is contextually convertible to bool work ?

#include <stdio.h>

int decreaseVal(int i){
    
    
    printf("deccrease val:  %d  \n",i);
    
    return --i;
}
 
int main () {
   // for loop execution
   
   int x;
   for( int a = 2; x=decreaseVal(a);a--) {

      printf("value of a: %d  \n",a);
   }
 
   return 0;
}

CodePudding user response:

All of the basic types in C have a default behavior when treated like a boolean. For ints, a value of zero is false and anything else is true. For pointers, anything but NULL is true, and NULL is false. A 0.0 float is false and I think everything else (including inf and NaN) are true. When your function returns an int, the for loop treats that as a bool and whet it gets to zero, the condition is false and the loop ends.

CodePudding user response:

In C Language any non zero value is considered as logical true.

If the result of the decreaseVal(a) is non zero the condition is met. The assignment does not change it. It is simply an additional operation. It should be inside the parentheses.

for( int a = 2; (x=decreaseVal(a));a--) {

Another example of the assignment as a logical expression (string copy function):

char *mystrcpy(char *dest, const char *src)
{
    char *wrk = dest;
    while((*wrk   = *src  ));
    return dest;
}
  •  Tags:  
  • c
  • Related