1

I am building my own version of the printf function in C and I need to replicate the original's behavior. I am trying to throw a compile error in a situation like the one written below:

// printf("%s %s", 3, 2);

How can I force a compile error when the code below gets executed? I wanted to display the following error: format specifies type 'char *' but the argument has type 'int'

Hakumai
  • 21
  • 1
  • 3
  • 4
    You write a compiler or you simply use an existing compiler's treat-all-warnings-as-errors option. – Jeff Holt Apr 29 '22 at 13:47
  • There might be compiler extensions that allow providing some attribute that marks a function to use `printf` like semantics. Naming the compiler might help a lot. – Gerhardh Apr 29 '22 at 13:48
  • Those compilers that emit diagnostics specific to the characteristics of particular library functions are able to do so because they contain code for those particular special cases. Standard C does not provide any way for your code to request such behavior from the compiler. – John Bollinger Apr 29 '22 at 13:52
  • Note that MS Visual C will *warn* about `printf` at *compile* time but at runtime it detects a `NULL` pointer and helpfully outputs "(null)" instead of dereferencing it. You can imitiate this run-time behaviour. But you are asking that the compiler verifies the arguments against a format string in a function it knows nothing about. How do you expect the compiler to know that your `%s` in a string literal means the same as in the library functions? Anyway, it's not an error, but a warning which the compiler gives as a courtesy. It is not required by the C standard. – Weather Vane Apr 29 '22 at 14:04
  • 1
    `gcc` provides the [`format` attribute](https://gcc.gnu.org/onlinedocs/gcc-11.3.0/gcc/Common-Function-Attributes.html#Common-Function-Attributes). As does [`clang`](https://clang.llvm.org/docs/AttributeReference.html#format). – G.M. Apr 29 '22 at 14:08
  • Possible duplicate: [How can I guarantee type safety of variadic arguments?](https://stackoverflow.com/questions/21295651/how-can-i-guarantee-type-safety-of-variadic-arguments) – Weather Vane Apr 29 '22 at 14:27

0 Answers0