I am currently developing a function that converts a list of values to integers. In the case of float types, we have the convenient float8in_internal_null()
function at toFloatList()
, which returns the appropriate float value if the conversion is successful, but returns NULL if the conversion of a list element fails.
However, when working with integers and using the atoi()
function, I encountered a limitation. Unlike float8in_internal_null()
, atoi()
does not return NULL when it fails to convert an element of the list to an integer. Instead, it returns 0.
Is there an alternative function within some library in AGE, that can help me achieve the desired behavior of returning NULL when a conversion to an integer is not possible? I would appreciate any guidance on this matter.
2
Answers
You can use check if the string you need to convert is zero, if it’s not zero and atoi() returns 0, then the string cannot be converted to an integer. Therefore, you can return or pass NULL.
Additionally, if you want you can use the function
age_tointeger
from AGE, calling this function inside your C function usingDirectFunctionCall
.In C or C++, there is no special value like null or None like other languages. NULL in C-C++ is just a macro that defines it as 0. So, unlike other languages, C-C++ functions return 0. You need to add an additional check to verify if the case is an error or if 0 is the right answer.
Instead, if you can use C++ libraries, you can also use
std::stoi
. It raises an exception in such cases, which can be handled.