这里不允许声明C中的错误

Ash*_*ngh 4 c

以下行有问题int (*f)(int, int) = (argv[2][0] == 'd'),编译时声明此处不允许声明.如果该行在开始时被声明,那么任何更好的方法都可以做到这一点.任何建议都会受到高度赞赏吗?

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

int encode(int ch, int key) { 
        if (islower(ch)) {
                ch = (ch-'a' + key) % 26 + 'a';
                ch += (ch < 'a') ? 26 : 0;
        }
        else if (isupper(ch)) {
                ch = (ch-'A' + key) % 26 + 'A';
                ch += (ch < 'A') ? 26 : 0;
        }
        return ch;
}

int decode(int ch, int key) { 
        return encode(ch, -key);
}

int main(int argc, char **argv) { 
        int ch;
        int key;

        if (argc < 2) {
                printf("USAGE: cipher <integer key> <encode | decode>\n");
                printf("Then, just type your text and it will automatically output the en/de crypted text! :)\n");
                return 1;
        }

        key = atoi(argv[1]);
        if (key < 1 || key > 25) {
                printf("Key is invalid, or out of range. Valid keys are integers 1 through 25.\n");
                return 1;
        }

        int (*f)(int, int) = (argv[2][0] == 'd') ? 
                decode : 
                encode;

        while (EOF != (ch=getchar()))
                putchar(f(ch, key));

        return 0;
}
Run Code Online (Sandbox Code Playgroud)

NPE*_*NPE 11

在C(C99之前)中,您必须在块的开头声明变量.

将代码编译为C99,或更改代码以便f在块的开头声明.

  • +1,直到C99.之前的任何事情(afaik)这是强制性的. (3认同)