0

I'm completely new to C, and I am attempting to run this example code on xcode, but it says build failed. I got the code exact like it is in the book, but it still won't run.

#include <stdio.h>
/* count characters in input; 2nd version */
int main()
{
    double nc;
    for (nc =0; getchar() != EOF; ++nc) {
        ;
    }
    printf("%.0f\n", nc);
}

Sorry if it's a noob question. All help is appreciated!

Mohit Jain
  • 30,259
  • 8
  • 73
  • 100
Kenshin
  • 177
  • 1
  • 9
  • 2
    You don't have a return statement in main. – 001 May 13 '14 at 02:30
  • 2
    What is the error you are getting? Paste the entire build output from xcode into this question. The code itself is valid, it may be a configuration issue. – Clarus May 13 '14 at 02:33
  • @Claris this is the output. adddsadsd 33334343434243 Program ended with exit code: 9 – Kenshin May 13 '14 at 02:37
  • 1
    Xcode 5.1 builds and runs this just fine. `main()` (uniquely) does not require an explicit `return` statement, it'll implicitly `return 0` for you if you leave it out. Typing input into the debug window and hitting `CTRL-D` to end produces the desired output for me. – Crowman May 13 '14 at 03:40

1 Answers1

0

The question code lacks a 'return {int value}' statement. I added this missing line, and ended up with the following code:

#include <stdio.h>
/* count characters in input; 2nd version */
int main()
{
   double nc;
   for (nc =0; getchar() != EOF; ++nc) {
       ;
      }
   printf("%.0f\n", nc);

   return(0);
}

The above compiled without errors or warnings using:

gcc -Wall -o test test.c

To run it requires that input to the program comes from a file. I made a file named 'junk.txt' with the following content (not including the braces):

[ adddsadsd 33334343434243] 

Then I executed the program using the following command:

./test < junk.txt

which generated the output:

25
Mahonri Moriancumer
  • 5,993
  • 2
  • 18
  • 28
  • 1
    As you're a learner, `Kenshin`, be aware that `return` isn't actually a function and can equally be written `return 0;`. Adding the brackets is a style preference. So you'll see it written without brackets elsewhere but don't worry about it: it means the same thing. – Tommy May 13 '14 at 04:16
  • 1
    Note that in C99 and C11, for compatibility with C++98 and later, you are permitted (but not AFAIAC recommended) to omit the `return` from the end of `main` and the result is equivalent to `return 0;`. Personally, I put the `return 0;` in the code. This permission was not present in C89, and by default GCC compiles for C89 (or GNU89). – Jonathan Leffler May 13 '14 at 05:53