简体   繁体   中英

Output behaviour of relational operators when used in printf - C Language

This is the code that i was trying :

#include <stdio.h>
main(){
    int k = 35;
    int x = (k==35);
    printf("%d %d %d %d", (k==35), k=50, (k>40), x); // gives output => 0 50 0 1
    printf("\n%s",k==35); // gives output => (null)
    return 0;
}

I was wondering that a relational check returns Boolean true or false . Even when converted to integer type it should become 0 for false and 1 for true . What am i missing?

Actually your k=50 with a single = is an assignment operator ; since it appears in a list of arguments, the order of evaluation of arguments is undefined, and you get stuck by undefined behavior .

The compiler is free to pass (k>40) before or after doing k=50

BTW, with GCC version 4.9 on Debian/Sid, when compiling your code with

gcc -Wall danglingcruze.c -o danglingcruze

I am warned by the compiler:

danglingcruze.c:2:1: warning: return type defaults to ‘int’ [-Wreturn-type]
 main(){
 ^
danglingcruze.c: In function ‘main’:
danglingcruze.c:5:37: warning: operation on ‘k’ may be undefined [-Wsequence-point]
     printf("%d %d %d %d", (k==35), k=50, (k>40), x); // gives output => 0 50 0 1
                                     ^
danglingcruze.c:5:37: warning: operation on ‘k’ may be undefined [-Wsequence-point]
danglingcruze.c:6:5: warning: format ‘%s’ expects argument of type ‘char *’, 
        but argument 2 has type ‘int’ [-Wformat=]
     printf("\n%s",k==35); // gives output => (null)
     ^

Order of evaluation of parameters in a function is not guaranteed. You are modifying k in one of the parameter and using its value in other parameters. That's why it invokes undefined behavior. An example of similar case

int i = 1;
printf("%d %d\n", i++, ++i); // Undefined behavior.
#include <stdio.h>
main(){
    int k = 35;
    int x = (k==35); // x =1
    printf("%d %d %d %d", (k==35), k=50, (k>40), x); // gives output => 0 50 0 1
    // k=50 changed your value
    printf("\n%s",k==35); // gives output => (null)
    // => printf %s + 0 => null 
    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM