gcc 4.7.2
c89
Hello,
I have this function that assigns a pointer to an another pointer that is an element of a string structure.
The purpose of this string structure is to get and set the length of the actual string.
However, I don’t understand why they have used a ternary operator. It doesn’t make sense to me. There doesn’t seem to be a condition apart from str->len = src. Which only assigns and doesn’t compare anything.
typedef struct tag_str_t str_t;
struct tag_str_t {
char *buf;
size_t len;
};
static void string_set(str_t *str, const char *src)
{
str->buf = (char*)src;
str->len = src ? strlen(src) : 0;
}
Would it be just as simple and more readable by doing just this?
str->len = strlen(src);
Many thanks for any suggestions,
The code:
is equivalent to:
I’ve added the parentheses and the extra expression to indicate where the components of the expression are. Your comment seems to indicate that you think
str->len = srcis the condition in the ternary operator, but that is wrong; assignment has a very low precedence.As Jesus Ramos also explained, the purpose of the test is to ensure that
strlen()is not called with a NULL pointer, which would lead to a crash.