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

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

 #include  #include  #include  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  \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  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; } 

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

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

在c89 / 90中,您必须在块的开头声明所有变量

但是在c99中,您可以使用-std=c99编译代码,如下所示:

gcc -Wall -std=c99 test.c -o test.out

除了NPE指出的部分,您可以使用typedef创建函数类型。 像这样:

typedef void FunctionType (int, int); 然后使用它(作为单独的类型)来创建函数指针。

使阅读变得容易。

该行应该在开始时声明

在C89中,定义必须在块中的任何语句之前发生。 如果你移动它,你不必移动整行(当然你不想在检查argv[2]的代码有效之前将整行移动到)。 只需移动f的定义:

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

任何更好的方法

在这种情况下,它不一定更好 ,但请注意,规则是​​块的开始,不一定是函数的开始。

所以,你可以写:

 { int (*f)(int, int) = (argv[2][0] == 'd') ? decode : encode; while (EOF != (ch=getchar())) putchar(f(ch, key)); } return 0; 

您可以轻松地了解有关此编码风格的论点。 有些人认为每个函数都应该预先定义它的所有变量,并且引入一个块来定义变量会混乱和/或混乱。 有些人(尤其是那些使用C ++和C的人)认为你应该将每个变量的范围限制为尽可能窄的代码,在函数开头定义所有内容的都是混乱和/或混乱的。 但即使他们可能会认为裸露的障碍过度。