1

The getchar(); line gives me the warning: this code has no effect.

#include <stdio.h>

int main()
{
    int this_is_a_number;

    printf( "Please enter a number: " );
    scanf( "%d", &this_is_a_number );
    printf( "You entered %d", this_is_a_number );
    getchar();
    return 0;
}

is there any solution?

alk
  • 69,737
  • 10
  • 105
  • 255
  • 1
    Which compiler are you using? And what was the command line that you used? – user3386109 Aug 27 '16 at 07:34
  • Mind that `int getchar(void);` is the prototype. Since you're not capturing the return value the compiler might give you a warning, but you could get away with that. – sjsam Aug 27 '16 at 07:34
  • I am using turbo c++ – Rissam Asghar Aug 27 '16 at 07:39
  • StackOverflow is using a Question and Answers model. You didn't submit a question. Please edit your post accordingly. – 2501 Aug 27 '16 at 07:42
  • Solution for removing the warning? Please elaborate. – 2501 Aug 27 '16 at 07:46
  • is there anything how to remove the warning? – Rissam Asghar Aug 27 '16 at 07:49
  • Which compiler are you using on which platform? Ideally, you should end the second `printf()` format string with a newline. But the 'code has no effect' warning is bogus — `getchar()` does have an effect. However, that effect will be to read the newline character after the number you entered, so it won't make your program stop until you type something. The input operation won't complete until you type a newline (unless you're doing contorted things that mean you wouldn't need to ask this question). – Jonathan Leffler Aug 27 '16 at 07:54
  • 5
    Use a proper compiler. Turbo C++ predates any standard and is really ancient. Or are you one of those whose school forces them to use that compiler? – Rudy Velthuis Aug 27 '16 at 07:54

2 Answers2

4

getchar() reads a key from the keyboard and returns the key. You would have to assign the value returned from the function to a variable:

int key;
key = getchar();

The warning is telling you that no variables will be changed when you call it the way you did. Certainly the code has some effect -- it reads from the keyboard, but that's all it does.

I taught Turbo C/C++ a long time ago so I won't say anything snarky about it. That was an amazing product back in its' day.

nicomp
  • 4,344
  • 4
  • 27
  • 60
1

As @nicomp answered, there is unused return value. You can get rid of it by casting result to void:

(void)getchar();
Roman Hocke
  • 4,137
  • 1
  • 20
  • 34