Why does “sizeof(a ? true : false)” give an output of four bytes?

后端 未结 7 1401
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-30 07:41

I have a small piece of code about the sizeof operator with the ternary operator:

#include 
#include 

int main()
{
         


        
相关标签:
7条回答
  • 2021-01-30 08:38

    There is no boolean datatype in C, instead logical expressions evaluate to integer values 1 when true otherwise 0.

    Conditional expressions like if, for, while, or c ? a : b expect an integer, if the number is non-zero it's considered true except for some special cases, here's a recursive sum function in which the ternary-operator will evaluate true until n reach 0.

    int sum (int n) { return n ? n+sum(n-1) : n ;
    

    It can also be used to NULL check a pointer, here's a recursive function that print the content of a Singly-Linked-List.

    void print(sll * n){ printf("%d -> ",n->val); if(n->next)print(n->next); }
    
    0 讨论(0)
提交回复
热议问题