开发者

Why do we need to specify type in format specifiers in the C++ printf function?

开发者 https://www.devze.com 2023-04-04 13:17 出处:网络
I\'ve done a bit of PHP and when you declare variables you do not need to declare the type (eg. string or int).

I've done a bit of PHP and when you declare variables you do not need to declare the type (eg. string or int).

However I have to tweak a very simple C file and, in order to get the print function to work correctly, I have to include a type specifier for the output of each variable.

Why isn't this type automatically inferred from the var开发者_运维问答iable itself?


C is a very simple language, by which I mean it offers a pretty minimal abstractions over the bare metal. The basic types come with no type information attached and even structs only get what type info you give them.

So in a typical implementation, when the compiler sees

int x, y;
float z;
int x = foo(y,z);

x, y, and z are likely one machine word which is interpreted as a 2s-complement integer for x and `y, and as a IEEE-754 floating-point value for z, and nothing else.

The the compiler does something like

  • advance the stack pointer to allow room for a return value
  • push y and z onto the stack (what order it does this in is implementation dependent)
  • push the current stack pointer+two instructions as the return address
  • branch to the entry point of foo.

(Decent chips provide some support to amke this easier, but still...)

Then foo

  • reads y and z from their locations relative the current stack value
  • does whatever on them
  • writes the return to x (again found by offset from the stack pointer)
  • branch back to the return address that the calling routine pushed.

If foo has not been instructed what type the passed arguments have (as in a variadac routine like printf) it won't know how big each argument on the stack is (actually c coerces the size of every variadac argument with a set of up-conversion rules to fix this issue), nor how to interpret it.

PHP on the other hand, provides a sophisticated abstraction over the bare machine, and can (must, in fact to do what it does) carry some identifing information around with each value it works with.


Because printf is part of the C-compatibility part of C++, where type detection wasn't so hot :-)

There is a disconnect between the specifiers in the format string and the data items being used for that specifier, for example:

printf ("String at memory %p is '%s'\n", mystr, mystr);
printf ("That character is '%c', ASCII code %d, hex %02x\n", mych, mych, mych);

If you use C++ streams for your output, this isn't so much of an issue.


The most common specifiers are:

%d/%i is for an integer
%c is for char
%s is for a string
%f is for float/double

For example:

int i = 1;
char hi[6] = "Hello"
printf("%d %s", i, hi);

would print

1 Hello

as given above, you can refer http://www.cplusplus.com/reference/clibrary/cstdio/printf/

0

精彩评论

暂无评论...
验证码 换一张
取 消