printf: function parameters calculated from right to left, left to right?

Making refrigerator panda @cnblogs 2019/8/3

 

1, problem

One day I write the following code:

unsigned char ReadByteFromFile ( FILE * fp )
{
  unsigned char ch;
  ...
  fread ( &ch, 1, 1, fp );
  ...
  return ch;
}
  
void main()
{
  ...
  printf ( "first byte = 0x%02x, second byte = 0x%02x\n", ReadByteFromFile ( fp ), ReadByteFromFile ( fp ) );
  ...
}

 

Printf line where the code is intended to continuously read two bytes from the file and print it out. Hypothesis is reading the file content for "0x01 02 03 04 ... ...", then the expected operating results are:

first byte = 0x01, second byte = 0x02

However, the actual operating results (Ubuntu, gcc compiler) has reversed a:

first byte = 0x02, second byte = 0x01

 

2, answer

Er er, interesting. Recall that a long time ago some class content and Internet search and found that there are no prescribed standard C compiler in order to calculate function parameters ( This form of argument-passing Known AS IS Call by value. At The Standard does not the Specify the Order for the any at The
Evaluation The arguments of. ). In other words, the original thinking printf () parameter values calculated in accordance with the order from left to right at run-time, in order to read the document here also in two bytes. But in fact, the result of the compiler output is printf () function calculates the parameters in the order from right to left, which led to the printf (first ReadByteFromFile () function (from left to right) after) read file, while the second ReadByteFromFile () but first read the file, and the final output expected in reverse order.

Or a user with a question on Stackoverflow presented to better illustrate the problem: Why the following code outputs the result is "45545."

main()
{
    int i = 5;
    printf ( "%d %d %d %d %d %d", i++, i--, ++i, --i, i); }

 Thus, in use the function if it involves several operations on the same variables / objects, the compiler must take into account the uncertainty in the order parameter calculation processing function. It is recommended that this happens, or now outside the function complete the calculation, then the results passed to the printf (). Of course, if the compiler can be agreed upon in order to calculate parameters (best left to right, in line with the daily habits), I was able to save some things that make the code look / write up some of the simple.

Guess you like

Origin www.cnblogs.com/pandabang/p/11293639.html