8

I wanted to print something using printf() function in C, without including stdio.h, so I wrote program as :

int printf(char *, ...);
int main(void)
{
        printf("hello world\n");
        return 0;
}

Is the above program correct ?

Happy Mittal
  • 3,667
  • 12
  • 44
  • 60
  • 5
    Your format string should be `const char*`. You could just locate `stdio.h` and read the definition there. Why, out of curiosity, don't you want to `#include `? – user229044 Nov 14 '10 at 18:30
  • 1
    how do you expect to print anything on the screen without including stdio.h ?? You'll have to write your own libraries .. it's suicidal :) – sdadffdfd Nov 14 '10 at 18:31
  • 12
    @bemace @Vic The act of including `stdio.h` doesn't link anything, header files don't work that way. This question is completely valid, and will work just fine. – user229044 Nov 14 '10 at 18:32
  • @meager : It was just a quiz question. – Happy Mittal Nov 14 '10 at 18:34

5 Answers5

19

The correct declaration (ISO/IEC 9899:1999) is:

int printf(const char * restrict format, ... );

But it would be easiest and safest to just #include <stdio.h>.

CB Bailey
  • 755,051
  • 104
  • 632
  • 656
13

Just:

man 3 printf

It will tell you printf signature:

int printf(const char *format, ...);

this is the right one.

peoro
  • 25,562
  • 20
  • 98
  • 150
4

I have no idea why you'd want to do this.

But it should be const char *.

Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
  • @Oli : Does only char* affect anything ? – Happy Mittal Nov 14 '10 at 18:35
  • 1
    @Charles: In C99, yes. That won't compile for anything earlier. – Oliver Charlesworth Nov 14 '10 at 18:35
  • @Charles Just `const char*` here. – user229044 Nov 14 '10 at 18:35
  • @Happy Yes, it defines a completely different function than `printf(const char*,...)`. – user229044 Nov 14 '10 at 18:36
  • @meager : If I don't write const, then isn't it guaranteed that library's printf is called ? – Happy Mittal Nov 14 '10 at 18:39
  • 1
    @meagar: This is not C++. I agree it's *wrong* to omit the `const`, but it does not "define a completely different function", only an incorrect prototype for the same function. (I suspect this wrong prototype is actually guaranteed to work anyway, but I'm not sure.) – R.. GitHub STOP HELPING ICE Nov 14 '10 at 18:56
  • 5
    @Happy Mittal: If you don't include all the required type qualifiers then you have provided a function prototype that isn't compatible with the function definition. C doesn't have function overloading so you can't be referring to any other function but attempting to call it with an incompatible prototype in scope technically leads to undefined behaviour. – CB Bailey Nov 14 '10 at 18:57
0

Here is another version of the declaration:

extern int printf (__const char *__restrict __format, ...);
Zorayr
  • 23,770
  • 8
  • 136
  • 129
-3
int printf(char *, ...);

works just fine, I don't know why people are telling you that char needs to be a const

lkl
  • 7