Why does printf return a value?

前端 未结 6 1832
自闭症患者
自闭症患者 2021-01-11 11:05

I know that printf returns a negative error or number of characters printed on success. Only reason to check this return value is if the execution of program s

6条回答
  •  离开以前
    2021-01-11 11:27

    There are a couple of situations in which you might want to check the return value of printf. One is to check for errors, as you mention; while there's usually nothing you can do if there's an error on printf, you may, if you're printing something really big, and get an error, decide to try printing it in smaller chunks.

    You may also be interested in how wide the output was; printf() returns the number of characters written on success. If you are trying to line up output, and you do a printf() with something of variable width, you can check the return value to find out how many characters were printed, so you know what column you are on. Of course, this only works if all of your characters are 1 column wide (which is true of most ASCII characters), but there are some cases in which this might be useful.

    snprintf() prints to a fixed-size buffer instead of stdout or a file. It will only print up to the size of the buffer that you give it; but it's possible that it would require more space to print the full string. It returns the amount of space it would have needed to print the full string; this way, you can use the return value to allocate a new buffer of the appropriate size, and try again, if your original buffer was too small. You almost always use the return value of snprintf(), for this reason.

提交回复
热议问题