3

I have certain doubts when wrong format strings are used in sprintf. Lets say for example %f is used as format specifier for an integer. Why is it not doing an implicit conversion? Consider the following program.

#include <stdio.h>
#include <string>
using namespace std;
int main()
{
    int i = 0;
    char temp[50];int a = 1;
    sprintf( temp, "%f",a);
    puts(temp);
    return 1;
}
C0D3R
  • 339
  • 1
  • 3
  • 12
  • 2
    *I have certain doubts when wrong format strings are used in sprintf* -- It is undefined behavior to do this. No need to ruminate on this. – PaulMcKenzie May 18 '16 at 14:10
  • Because this is `C standart library`. Use `cout` - it auto detects type and doesn't need format specifiers – fnc12 May 18 '16 at 14:16
  • `cout` is not as easy to use for many use-cases (e.g. printing a numeric value or pointer as a specific sized hex value with '.' as the padding). Plus it does not print to a string, in which cases you would need a string stream. – Dennis May 18 '16 at 14:19
  • Note that this is not only `sprintf`, but `printf`, `scanf`, `snprintf`, etc. -- undefined behavior. How about `char ch = 'x'; sprintf(temp, "%f", ch);`? The `sprintf` call is expecting a variable that is `sizeof(float)` bytes in size, but gets a variable that is 1 byte in size. So where is sprintf() going to grab the extra bytes from? It could be that the stack is used – PaulMcKenzie May 18 '16 at 14:31

2 Answers2

3

Because the function has no idea what types you are sending it unless you give the proper parameters.

Variadic functions by definition don't have any type information for the undefined arguments and must themselves determine what to get from the given data.

Sami Kuhmonen
  • 30,146
  • 9
  • 61
  • 74
2

The sprintf function has a varargs parameter list.
The compiler usually doesn't parse the second argument (the format string) in order to determine the type of the successive parameters.
Implicit conversion is therefore not possible.

Robert Kock
  • 5,795
  • 1
  • 12
  • 20
  • Compilers may check the params types against the format string and issue a warning, but that's it ... – Unda May 18 '16 at 14:57