Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does itoa() modify the passed char[] instead of returning char[]?

Tags:

c++

c

Is there any reason why the itoa() function returns void and stores the result in the char[] array passed to it, instead of returning char[] ?

like image 657
Ryan Avatar asked Dec 07 '22 05:12

Ryan


1 Answers

The reason is that the function expects the caller to allocate and supply the buffer. This is very standard in C. If the function returned a new buffer, the caller would have to take care of deallocating it, and it would force the buffer to be dynamically allocated. By asking the caller to supply the buffer, the function allows the buffer to be allocated with automatic storage, or dynamically allocated.

And in fact, the versions of itoa that I am familiar with do indeed return the buffer that the caller provided, rather than return void.

like image 196
David Heffernan Avatar answered May 23 '23 05:05

David Heffernan