-6

When compiling my code below, it says that f is uninitialized. How do I initialize a character and why do I need to? My intention is to end the loop when f is entered and stored in c.

#include <stdio.h>
#include <string.h>
int main(void)
{
  int count= 0;
  char c,f;

  printf("Input a character:\n");
  do
  {
    c = getchar();
    count++
  }while(c!=f);
  printf("number of characters: %d", count);
  return 0;
}
gre_gor
  • 6,669
  • 9
  • 47
  • 52
oxodo
  • 149
  • 5

3 Answers3

3

f is the name of the variable not the character 'f' !

you need to initialize char f = 'f';

fievel
  • 480
  • 3
  • 9
2

You need to initialize the variable, because otherwise c != f is comparing c with whatever indeterminate value happens to be in the f variable.

If you want to test whether they typed the letter f, you should be comparing with a literal, not a variable.

do {
    c = getchar();
    count++;
} while (c != 'f');
Barmar
  • 741,623
  • 53
  • 500
  • 612
0

How do I initialize a character?

You does not initialize a character, you initialize a variable.

And why do I need to?

When you declare a local variable, this variable are allocated on the stack and it's value is the current value into that position at the stack (i.e. garbage).

So you need to set a value to that variable to avoid a undefined behavior of the program. In your specif case this value is: 'f'. The single quotes means that f is a character, this is the type of data that your variable (char) expects.