Search code examples
cscanfgetchar

getchar() causes error while scanf don't


#include<stdio.h>
void main() {
char ch;
ch=getchar();
printf("%d",ch);
}

This gives me error NZEC (non zero exit code) but when I use-

#include<stdio.h>
void main() {
char ch;
scanf("%c",&ch);
printf("%d",ch);
}

No execution error and accepts solution What's wrong with getchar() ?

I am quite new to C so don't know much I checked few answers on difference between scanf and getchar but I could not understand. Please help me in understanding this behaviour.

Solution: I did not know that my query is related to this question: What should main() return in C and C++?

Moreover both of these are working-

#include<stdio.h>
void main() {
int ch;
ch=getchar();
printf("%d",ch);
}

changing char to int and-

#include<stdio.h>
int main(void) {
char ch;
ch=getchar();
printf("%d",ch);
return 0;
}

changing void to int


Solution

  • Both are undefined behaviours because main should return int as defined by the C standard. It's especially important when you are checking its return code.

    Change the definition to:

    int main(void)
    {
        ...
    }
    

    Note that since C99, main doesn't need to explicitly return any value. It's as if you had return 0; at the end. But if you are using C89, you are required to return a value explicitly (or call exit).