Home > other >  Ternary operators in C, wrong output
Ternary operators in C, wrong output

Time:01-17

I have the bellow code that is asking to identify any errors:

main( )
{
int kk = 65 ,ll ;
ll = ( kk == 65 : printf ( "\n kk is equal to 65" ) : printf ( "\n kk is not equal to 65" ) ) ;
printf( "%d", ll ) ;
}

I have corrected it to the bellow:

int main( )
{
int kk = 65, ll ;
ll = kk == 65 ? printf ( "\n kk is equal to 65" ) : printf ( "\n kk is not equal to 65" );
printf( "%d", ll ) ;
}

I would expect the output to be kk is equal to 65, however, I am getting 'kk is equal to 6519'

Can anyone please have a look into this and help me see the reason for this?

Thank you very much,

Cris G

CodePudding user response:

The printf() function returns the number of characters printed to stdout. Therefore, the value 19 is assigned to the variable ll. The expression "\n kk is equal to 65" is printed on the screen, followed by the value of the variable ll.

#include <stdio.h>

int main( )
{
    int kk = 65, ll;
    ll = (kk == 65) ? printf( "\n kk is equal to 65" ) : printf ( "\n kk is not equal to 65" );
    
    printf("\nll: %d", ll);
    printf("\nNumber of character: %d", printf( "\n kk is equal to 65" ));

    return 0;
}

This program generates the following output:

 kk is equal to 65
ll: 19
 kk is equal to 65
Number of character: 19

CodePudding user response:

The " kk is not equal to 65" part comes from the printf("\n kk is equal to 65")and the "19" comes from the result of the previous mentioned printf which returns 19 as the number of characters written by printf for the string "\n kk is equal to 65".

  •  Tags:  
  • Related