Why does getchar make a call to printf to stop working?

I wrote a program that takes an input character and displays this character, like this

int ch = getchar();
printf("%c", ch);

It worked as I expected. Then I decided to welcome you and print first Hello.

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 the "type"

I have not seen why adding the first line will cause this to happen. In any case, I reorganized the program to get rid of the announcement int, and the errors magically disappeared.

printf("Hello!\n");
printf("%c", getchar());

What's happening? What magic causes these errors and then disappears?

+3
source share
4

C89, C99.

, c99.
, . gcc-4.3.4


:

:
:

int ch;
printf("Hello!\n");
ch = getchar();
printf("%c", ch);

:

printf("Hello!\n");
{ 
    int ch = getchar();
    printf("%c", ch);
}

:

, , gcc, c99.

+3

c, - . :

int ch;
printf("Hello!\n");
ch = getchar();
printf("%c", ch);
+5

C C99 " ", . C , ++. , C99, .

, , - .

+2

, C. , C89. - (, ) : ch:

int ch = getchar();
printf("Hello!\n");
printf("%c", ch);

, , . ? ? Linux? Mac?

, . getchar .

getchar scanf ( "% d", & ch). , getchar char, ch char, , itoa, char .

0

All Articles