Reputation: 142939
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?
Upvotes: 3
Views: 1248
Reputation: 577
Probably, you are using an pretty old C compiler. Probably one with C89 support. Using so forces you to declare any variable before anything within a block, (eg an function or main) Two ways out: Declare ch first:
int ch = getchar();
printf("Hello!\n");
printf("%c", ch);
or, even better, try changing your compiler. What OS are you using? Windows? Linux? Mac?
Also, a quick note. You are using getchar to get an integer number.
Try using, instead of getchar, scanf("%d", &ch). Or, if you really needs to use getchar, and to print it as a char, declare ch as a char itself, and, if you need to use it as an integer again, use the itoa function, that transforms a char to an integer.
Upvotes: 0
Reputation: 206546
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:
int ch;
printf("Hello!\n");
ch = getchar();
printf("%c", ch);
Or
Create a new block for declaring the variable:
printf("Hello!\n");
{
int ch = getchar();
printf("%c", ch);
}
Suggestion:
You should really change your compiler because if i remember correctly gcc supported this as compiler extension even prior to c99.
Upvotes: 3
Reputation: 95335
Versions of C prior to C99 did not allow “mixed declarations and code”, meaning you had to declare all of your variables at the beginning of the scope. Modern-day C compilers allow mixed declarations and code, as do C++ compilers. Some non-C99 compilers even allow it as an extension.
I assume this was to make it easier for a compiler to determine how much space would actually be required on the stack, or something along those lines.
Upvotes: 2
Reputation: 10507
If you're using an older c compiler , you have to make all variable declarations BEFORE anything else. Try:
int ch;
printf("Hello!\n");
ch = getchar();
printf("%c", ch);
Upvotes: 5