getop()中的澄清

时间:2015-05-12 07:15:28

标签: c kernighan-and-ritchie

Dennis Ritchie" C编程语言"书, 在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] = '\0';

    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] = '\0';

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

    return NUMBER;
}

3 个答案:

答案 0 :(得分:8)

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

答案 1 :(得分:0)

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

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

答案 2 :(得分:0)

零char将在稍后被覆盖,除非(!isdigit(c) && c != '.')的测试为真,以便函数尽早返回。一些编码指南会阻止函数中间的返回,顺便说一句。

仅当函数提前返回时,s[1] = '\0'才相关。因此,人们可以编码

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

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

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

这不是非典型的。处理有效数据通常简单明了;处理所有意外事件会使代码变得错综复杂和巴洛克式。