I wrote a program that accepts a character of input and outputs that character, like this
int ch = getchar();
printf("%c", ch);
It worked like I expected. Then I decided to be welcoming and print Hello first.
printf("Hello!\n");
int ch = getchar();
printf("%c", ch);
To my surprise, this caused the compiler to throw two errors:
error C2065: ‘ch’ : undeclared identifier
error C2143: syntax error : missing ‘;’ before ‘type’
I didn’t see why adding the first line would cause that to happen. Anyway, I refactored the program to get rid of the int declaration and the errors magically disappeared.
printf("Hello!\n");
printf("%c", getchar());
What’s going on? What’s the magic that causes these errors to appear and then disappear?
Creating new variables after the start of a block was not allowed in C89 standard but is allowed in the newer C99 standard.
You are using a older compiler or a compiler not fully compliant to c99.
Your code example should work as is on any good compiler. Works on gcc-4.3.4
Alternate Solutions:
You can get rid of the problems in two ways:
Declare the variable at the begining of the block:
Or
Create a new block for declaring the variable:
Suggestion:
You should really change your compiler because if i remember correctly gcc supported this as compiler extension even prior to c99.