Why in conditional operator (?:), second and third operands must have the same type?

后端 未结 5 1386
挽巷
挽巷 2021-01-31 19:35

Why in conditional operator(?:), second and third operands must have the same type?

My code like this:

#include 

        
5条回答
  •  难免孤独
    2021-01-31 19:44

    the ?: expression will produce a value(called rvalue), which is to be assigned to a variable(which is called lvalue), as J.N. metioned, C++ is a statically typed language, lvalue must be known at compile time.

    int num = a>b ? a : "eh, string?";
    

    The code above won't compile, cause the variable num can only hold an int, string is not allowed.

提交回复
热议问题