1

Why does this code work:

    #include <stdio.h>

    int main()
    {
        int x = isspace(getchar());
        printf("%d", x);
        return 0;
    }

Whenever I enter whitespace isspace() returns 8 and when I don't, it gives 0.

Shouldn't this produce an error at compile time? I didn't add #include <ctype.h> at the top. So why this is allowed?

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
London
  • 65
  • 3

2 Answers2

5

You're seeing this because your compiler (sadly, still) supports implicit declaration of a function.

If you enable strict checking, you compiler should refuse to compile the code. On and above C99, the implicit function declaration has been made non-standard. (To add, hopefully, future versions of compiler will strictly disallow this, by default.)

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
1

Sometimes a specific implementation of the C Standard Libraries will support one header by including another itself: in your case, stdio.h may be including - either directly or indirectly - the isspace declaration, which might itself be directly in ctype.h or in some other file that ctype.h would include. You could test for this by executing just your preprocessing stage, as in...

gcc -E myprog.c | grep isspace

Another thing that can happen is that compilers hardcode implementations of common functions, like say strlen, so they can e.g. perform it at compile time on string literals.

Despite it "working", you would ideally directly include the headers you'll need, so if another compiler/implementation - or a later release of the same - doesn't have the same quirks your code will still compile.

Tony Delroy
  • 102,968
  • 15
  • 177
  • 252