I have a function that takes two strings and returns another string (if you must know, its my implementation of strjoin).
Now, I want to make it so that if one of the input strings is NULL, it will return the other string.
The most immediate way I figured is simply
if (!str1)
return (str2);
if (!str2)
return (str1);
But then I thought, let’s go fancier, let’s try to save a few lines and learn something in the process. So I figured there must be some operator whose result is whichever one of the two values is not zero, and I happened upon the bitwise OR operator (|).
When I tried to implement the following code, it said that these operators only work on integer type values, which kinda makes sense, I guess, but I’d like to know if there is a way to do this same exact thing with non-integers 🙂
if (!(str1 && str2))
return (str1 | str2)
Now, because the problem was the data type, I figured I’ll just typecast the shit out it. So I changed it into
if (!(str1 && str2))
return ((char *)((int)str1 | (int)str2))
It’s not pretty, but I figured it would work somehow. What happened was actually a segfault! But I honestly cannot explain why this would result in a segfault O_o Can someone explain?