V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
Distributions
Ubuntu
Fedora
CentOS
中文资源站
网易开源镜像站
zhongshaohua
V2EX  ›  Linux

关于宏定义的安全性,下面为什么会输出- 1?

  •  
  •   zhongshaohua · Jun 12, 2016 · 3025 views
    This topic created in 3607 days ago, the information mentioned may be changed or developed.
    #define ARRAY_SIZE(a) (sizeof(a)/sizeof(a[0]))

    int fun(void)
    {
    int array[] = {1, 2, 3, 4, 5};

    if ((ARRAY_SIZE(array) - 2) > -1) {
    /* xxx */
    return 0;
    }

    return -1;
    }
    5 replies    2016-08-13 21:29:52 +08:00
    sen506
        1
    sen506  
       Jun 12, 2016 via Android   ❤️ 1
    int 转成 uint 去运算了,,
    azh7138m
        2
    azh7138m  
       Jun 12, 2016 via Android
    楼上正解, sizeof 返回的是无符号数,运算符两边存在无符号数的时候就会把带符号数转换为无符号数
    htfy96
        3
    htfy96  
       Jun 12, 2016
    因为 ARRAY_SIZE(array)-2 是 unsigned long ,比-1 的 int 阶高,所以 int 会被转成 unsigned long
    zhongshaohua
        4
    zhongshaohua  
    OP
       Jun 13, 2016
    感谢楼上各位老司机
    liashui
        5
    liashui  
       Aug 13, 2016
    If both operands have the same type, then no further conversion is needed.
    Otherwise, if both operands have signed integer types or both have unsigned
    integer types, the operand with the type of lesser integer conversion rank is
    converted to the type of the operand with greater rank.
    Otherwise, if the operand that has unsigned integer type has rank greater or
    equal to the rank of the type of the other operand, then the operand with
    signed integer type is converted to the type of the operand with unsigned
    integer type.
    Otherwise, if the type of the operand with signed integer type can represent
    all of the values of the type of the operand with unsigned integer type, then
    the operand with unsigned integer type is converted to the type of the
    operand with signed integer type.
    Otherwise, both operands are converted to the unsigned integer type
    corresponding to the type of the operand with signed integer type.
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   993 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 35ms · UTC 19:31 · PVG 03:31 · LAX 12:31 · JFK 15:31
    ♥ Do have faith in what you're doing.