Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

atoi is a standard function. But itoa is not. Why?

Why this distinction? I've landed up with terrible problems, assuming itoa to be in stdlib.h and finally ending up with linking a custom version of itoa with a different prototype and thus producing some crazy errors.

So, why isn't itoa not a standard function? What's wrong with it? And why is the standard partial towards its twin brother atoi?

like image 736
Pavan Manjunath Avatar asked Apr 15 '12 14:04

Pavan Manjunath


People also ask

What is the difference between Atoi and itoa?

atoi is the 'ascii to integer' function and itoa is the reverse, the 'integer to ascii' function. You would use atoi to convert a string, say, “23557” to the actual integer 23557. Similarly, you would use itoa to convert an integer, say 44711, to the equivalent string “44711”. Very handy.

Is itoa a standard function?

C Programming/stdlib. h/itoaThe itoa (integer to ASCII) function is a widespread non-standard extension to the standard C programming language. It cannot be portably used, as it is not defined in any of the C language standards; however, compilers often provide it through the header <stdlib.

Is there an itoa function in C?

itoa () function is used to convert int data type to string data type in C language.

How is function itoa () written?

here is the function prototype of itoa function: char* itoa(int val, char* string, int base); It converts val(integer) to a string and stores it in string(character array) and returns the same.


2 Answers

No itoa has ever been standardised so to add it to the standard you would need a compelling reason and a good interface to add it.

Most itoa interfaces that I have seen either use a static buffer which has re-entrancy and lifetime issues, allocate a dynamic buffer that the caller needs to free or require the user to supply a buffer which makes the interface no better than sprintf.

like image 84
CB Bailey Avatar answered Oct 22 '22 10:10

CB Bailey


An "itoa" function would have to return a string. Since strings aren't first-class objects, the caller would have to pass a buffer + length and the function would have to have some way to indicate whether it ran out of room or not. By the time you get that far, you've created something similar enough to sprintf that it's not worth duplicating the code/functionality. The "atoi" function exists because it's less complicated (and arguably safer) than a full "scanf" call. An "itoa" function wouldn't be different enough to be worth it.

like image 44
bta Avatar answered Oct 22 '22 08:10

bta