![](/img/trans.png)
[英]I am using struct in Turbo C++ — it is giving error declaration is not Allowed Here
[英]Declaration not allowed here error in 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;
}
在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的人)認為你應該將每個變量的范圍限制為盡可能窄的代碼,在函數開頭定義一切的東西都是混亂和/或混亂的。 但即使他們可能會考慮過度裸露。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.