Question

#include <stdio.h>
int main(void)
{ 
    getchar();
    return 0;
}

In the above sample code, if the user enters a character, then what will happen to it.
Will it be placed at some memory location or not?

Était-ce utile?

La solution

It will be discarded for sure after reading.

Let's understand it with a simple example

int i = 1;
i++;

What second statement will do actually. When it executes, the the value of i is fetched from memory but there is no other variable to assign this value to, and it gets discarded, and the increment may take place at any time between the previous and next sequence point.
Similarly getchar(); will read a character but it will be discarded as there is no assignment of this value to any memory location.

Autres conseils

Technically what will probably happen is that the character code will be put into a processor register by the getchar function. Normally the calling code will then copy that into a memory location, but in your example it will not stored anywhere in memory (where should it go). Then, soon afterwards the processor register will be overwritten with some other data.

So, the value will be discarded.

A lot might go on behind the scene.

Since getchar() is a Standard C standard I/O function, it is very likely reading from a buffered stream. This means

  • a buffer will be filled (stdin is line buffered by default)
  • a stream index will be initialized and possibly incremented
  • the character value will be placed in a register or it may not. C compiler optimizers range from stupid to smart.
  • other actions that the stdio library may perform, but which we can only speculate about since they don't affect your program in a detectable way

In short, doing nothing with a function return value is totally sane. It has no adverse effects. The C language even provides the (void) cast to explicitly state such an intention.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top