getop() 中的说明

Clarification in getop()

在丹尼斯·里奇 "C programming Language" 的书中, 在 getop 函数中, 他说 s[1]='\0' 他为什么要在索引 1 上结束数组?有什么意义和需要?

在后面的部分他确实使用了数组的其他部分..

int getch(void);
void ungetch(int);

/* getop: get next character or numeric operand */
int getop(char s[])
{
    int i, c;
    while ((s[0] = c = getch()) == ' ' || c == '\t')
        ;
    s[1] = '[=10=]';

    if (!isdigit(c) && c != '.')
        return c; /* not a number */

    i = 0;
    if (isdigit(c)) /* collect integer part */
        while (isdigit(s[++i] = c = getch()))
            ;

    if (c == '.') /* collect fraction part */
        while (isdigit(s[++i] = c = getch()))
            ;
    s[i] = '[=10=]';

    if (c != EOF)
        ungetch(c);

    return NUMBER;
}

因为函数可能 return 在读取剩余输入之前,然后 s 需要是一个完整的(并终止的)字符串。

s[] 可能只是一个数字操作数,如“+”、“-”等

在这种情况下,s[1] 必须是 '[=11=]' 才能让 s 成为一个正确的字符串。

零字符稍后将被覆盖,除非测试 if (!isdigit(c) && c != '.') 为真以便函数 returns 提前。一些编码指南会阻止 returns 从函数的中间,顺便说一句。

只有当函数returns早的时候才与s[1] = '[=12=]'相关。因此,可以编码

int getop(char s[])
{
    int i, c;
    while ((s[0] = c = getch()) == ' ' || c == '\t')
        ;

    if (!isdigit(c) && c != '.')
    {   
         s[1] = '[=10=]'; /* Do this only when we return here */
         return c; /* not a number */
    }
    i = 0;
    if (isdigit(c)) /* collect integer part */
    /* ... */

这是简洁的代码。这些人知道他们的语言和算法。但是该片段缺乏错误处理,因此依赖于正确的输入(无效输入可能会让 s 为空或让 s 溢出)。

这并非不典型。有效数据的处理通常直接而简短;处理所有突发事件会使代码变得复杂和巴洛克式。