-2

I am not able to print the count c in this c code.

I have tried in a terminal with many lines.

#include<stdio.h>
main()
{

    long c=0;
    while(getchar()!=EOF)
        ++c;
    printf("%ld\n",c);
}

expected result should be characters we provide.

  • 1
    Doesn't your compiler issue a warning about using `long c` uninitialized? – Blaze Jun 11 '19 at 07:51
  • Local (automatic) variables are not initialized. Their values are *indeterminate*. Any descent text-book or tutorial or teacher should have taught you that. – Some programmer dude Jun 11 '19 at 07:52
  • 1
    `main()` should be `int main(void)`. And for future reference, please indicate in your question what output you got. I expect your program would have printed some arbitrary integer value. (It "worked" for me, apparently because `c` just happened to have the initial value zero.) – Keith Thompson Jun 11 '19 at 07:55
  • My program did not give me compile error.It just not complete in terminal.I want to know about EOF . – Hardik Khanesa Jun 11 '19 at 08:01
  • I suspect that, once you fix the issues pointed out in the comments, your question will be answered by this: https://stackoverflow.com/questions/1118957/c-how-to-simulate-an-eof – Bob__ Jun 11 '19 at 08:11

2 Answers2

2

Your program exposes undefined behaviour, since c is not initialized. Actually every answer predicting the result of c is wrong, even if one said "it's garbage". Your variable c is a local variable with automatic storage duration, so it does not get initialized per se; In expression ++c, your variable is an lvalue as it designates an object. See what the standard says concerning lvalues and non-initialized (cf., for example this online C11 standard draft):

6.3.2.1 Lvalues, arrays, and function designators

1...

2... If the lvalue designates an object of automatic storage duration that could have been declared with the register storage class (never had its address taken), and that object is uninitialized (not declared with an initializer and no assignment to it has been performed prior to use), the behavior is undefined.

Stephan Lechner
  • 34,891
  • 4
  • 35
  • 58
1

To signal EOF in a terminal you type a special key, depending on the operating system you use. Examples:

  • On Windows (cmd) it is CtrlZ.
  • On Linux it is CtrlD.

You need to type this at the beginning of a line.

the busybee
  • 10,755
  • 3
  • 13
  • 30