有什么不对的1988年C code吗? [英] What's wrong with this 1988 C code?

查看:84
本文介绍了有什么不对的1988年C code吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图编译这块code从书C语言程序设计(K&安培; R)。它是UNIX程序厕所的一个最基本的版本:

I'm trying to compile this piece of code from the book "The C Programming Language" (K & R). It is a bare-bones version of the UNIX program wc:

#include <stdio.h>

#define IN   1;     /* inside a word */
#define OUT  0;     /* outside a word */

/* count lines, words and characters in input */
main()
{
    int c, nl, nw, nc, state;

    state = OUT;
    nl = nw = nc = 0;
    while ((c = getchar()) != EOF) {
        ++nc;
        if (c == '\n')
            ++nl;
        if (c == ' ' || c == '\n' || c == '\t')
            state = OUT;
        else if (state == OUT) {
            state = IN;
            ++nw;
        }
    }
    printf("%d %d %d\n", nl, nw, nc);
}

和我得到了以下错误:

$ gcc wc.c 
wc.c: In function ‘main’:
wc.c:18: error: ‘else’ without a previous ‘if’
wc.c:18: error: expected ‘)’ before ‘;’ token

这本书的第二版是1988年,我pretty新C.也许它与编译器的版本做也许我只是痴人说梦话。

The 2nd edition of this book is from 1988 and I'm pretty new to C. Maybe it has to do with the compiler version or maybe I'm just talking nonsense.

我已经看到了现代的C code不同的使用功能:

I've seen in modern C code a different use of the main function:

int main()
{
    /* code */
    return 0;
}

这是一个新的标准或我仍然可以使用类型少主?

Is this a new standard or can I still use a type-less main?

推荐答案

您的问题是与在你的preprocessor定义 OUT

#define IN   1;     /* inside a word */
#define OUT  0;     /* outside a word */

注意如何在每个它们的尾随分号。当preprocessor扩展它们,你的code将大致如下:

Notice how you have a trailing semicolon in each of these. When the preprocessor expands them, your code will look roughly like:

    if (c == ' ' || c == '\n' || c == '\t')
        state = 0;; /* <--PROBLEM #1 */
    else if (state == 0;) { /* <--PROBLEM #2 */
        state = 1;;

这是第二个分号使得其他有没有previous 如果作为搭配,因为你是不使用大括号。所以,从的preprocessor定义删除分号 OUT

That second semicolon causes the else to have no previous if as a match, because you are not using braces. So, remove the semicolons from the preprocessor definitions of IN and OUT.

的教训这里是的 preprocessor语句没有以分号结束。

此外,你应该总是使用大括号!

Also, you should always use braces!

    if (c == ' ' || c == '\n' || c == '\t') {
        state = OUT;
    } else if (state == OUT) {
        state = IN;
        ++nw;
    }

有没有挂 - 其他模糊上面code

There is no hanging-else ambiguity in the above code.

这篇关于有什么不对的1988年C code吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆