Understanding an uncommon argument to main

后端 未结 2 697
一向
一向 2021-02-01 20:34

The following question was given in a college programming contest. We were asked to guess the output and/or explain its working. Needless to say, none of us succeeded.



        
2条回答
  •  北荒
    北荒 (楼主)
    2021-02-01 21:07

    Ok, _ is just a variable declared in early K&R C syntax with a default type of int. It functions as temporary storage.

    The program will try to read one byte from standard input. If there is input, it will call main recursively continuing to read one byte.

    At the end of input, read(2) will return 0, the expression will return 0, the write(2) system call will execute, and the call chain will probably unwind.

    I say "probably" here because from this point on the results are highly implementation-dependent. The other parameters to write(2) are missing, but something will be in the registers and on the stack, so something will be passed into the kernel. The same undefined behavior applies to the return value from the various recursive activations of main.

    On my x86_64 Mac, the program reads standard input until EOF and then exits, writing nothing at all.

提交回复
热议问题