以下代码如何将输出作为-99?

时间:2018-04-22 14:51:05

标签: c

以下是一个C代码段,str初始化为" face":

char *str = "face";
printf("%d\n", -2[str]);

4 个答案:

答案 0 :(得分:5)

首先,我们需要解析有问题的表达式:-2[str]中有两个运算符 - 一个下标运算符[]和一元减号运算符-。下标运算符的higher precedence比一元减去printf,因此2[str]会打印2[str] *的否定。

有许多Q& As解释str[2]str[2]相同,所以我不打算重复解释;你可以阅读in this Q&A

最后,'c'的值为99,代表系统上-99的代码。否定将应用于该值,因此-将被打印。

*请注意,class SearchAppBar extends StatefulWidget { @override _SearchAppBarState createState() => new _SearchAppBarState(); } class _SearchAppBarState extends State<SearchAppBar> { Widget appBarTitle = new Text("AppBar Title"); Icon actionIcon = new Icon(Icons.search); @override Widget build(BuildContext context) { return new Scaffold( appBar: new AppBar( centerTitle: true, title:appBarTitle, actions: <Widget>[ new IconButton(icon: actionIcon,onPressed:(){ setState(() { if ( this.actionIcon.icon == Icons.search){ this.actionIcon = new Icon(Icons.close); this.appBarTitle = new TextField( style: new TextStyle( color: Colors.white, ), decoration: new InputDecoration( prefixIcon: new Icon(Icons.search,color: Colors.white), hintText: "Search...", hintStyle: new TextStyle(color: Colors.white) ), );} else { this.actionIcon = new Icon(Icons.search); this.appBarTitle = new Text("AppBar Title"); } }); } ,),] ), ); } } 不是整数常量的一部分,因为in C integer constants do not include sign

答案 1 :(得分:4)

问题中的代码是:

char *str = "face";
printf("%d\n", -2[str]);

让我们明确一点:这很可怕,任何编写该代码的人都应该重写它。

接近这个时,有两个部分混淆:

  1. Why is a[i] == i[a]?
  2. -2[str]如何评估?
  3. 链接问题涵盖(1)广泛。阅读它。

    要解决第二部分,请考虑另一个方案:

    #include <stdio.h>
    
    int main(void)
    {
        char data[] = "XYZface";
        char *str = &data[3];
        printf("[%s] %d %d %d (%c)\n", str, -2[str], -(2[str]), (-2)[str], (-2)[str]);
    
        return 0;
    }
    

    输出:

    [face] -99 -99 89 (Y)
    

    为什么呢? -2[str]符号相当于-str[2](您已阅读链接的问答A,避难所?)而不是str[-2],因为没有负数字数。< / p>

    阅读C11 §6.4.4.1 Integer constants:那里没有减号。当您编写-2时,您有一元减号运算符和一个文字2。大多数情况下,它与负数2相同,但在与较高优先级的运算符(例如下标)混合时则不会。下标等§6.5.2 Postfix operators优先于§6.5.3 Unary operators,例如否定。

    我们也很清楚:问题的代码中没有未定义的行为(或者我的信任)。从技术上讲,字母'c'+99)的值是实现定义的,但很少有现存系统'c'的整数值不是99(但请参阅EBCDIC对于答案不同的代码集。)

答案 2 :(得分:3)

让我们剖析:

-2[str]

-(2[str])

因为运算符优先级。请注意,-2不是直接整数文字; 2是,它可以接收一元运算符-,但在此之前,[]运算符已应用。
下一步是

-(str[2])

因为(众所周知的好奇事实)a[i]==i[a]

-('c')

由于格式字符串%d,这被视为负int,其ASCII值的绝对值为'c'

-(99)
-99

(这当然是几位评论者的专有技术汇编: Jonathan Leffler,StoryTeller和我自己的一点点。)

答案 3 :(得分:1)

正如评论中所解释的,代码的工作原理如下:

-(2[str]) =&gt; -(*(2 + str)) =&gt; -str[2]

由于str[2]'c',其ASCII值为99。因此输出为-99

谢谢,讲故事的人要清理它。