What does mean of " return p ? memcpy(p, s, len) : NULL; " in below code? (More generally, what is the conditional operator, a ? b : c
?)
char * strdup(const char * s)
{
size_t len = 1+strlen(s);
char *p = malloc(len);
return p ? memcpy(p, s, len) : NULL;
}
This syntax is called a ternary operator and you can think of it as of simplified if statement. return p ? memcpy(p, s, len) : NULL;
is the same as:
if(p)
return memcpy(p, s, len);
else
return NULL;
memcpy()
function returns a pointer to dest, which is a first argument of memcpy and in your case this is p
. So, if p
has value different than 0 (pointer is not NULL) then return that pointer. Otherwise, return NULL.
It means execute and return memcpy(p, s, len)
, unless p==0
. If p==0
, it will return NULL
, and not execute memcpy(p, s, len)
.
Read https://en.wikipedia.org/wiki/%3F:#C for more.
Also, to paraphrase http://man7.org/linux/man-pages/man3/memcpy.3.html : The memcpy() function copies len bytes from memory area p to memory area s. The memory areas must not overlap.
That is, if we have the below memory:
p s
[][1][2][3][][][4][5][6][]
and len == 3, then when memcpy is called we get:
p s
[][1][2][3][][][1][2][3][]
Finally, the value a function returns is the value it evaluates to if you then use it in an expression; if foo()
returns 5, print(foo());
prints 5.
This is a ternary operator in C.
p ? memcpy(p, s, len) : NULL;
It means that if the first condition is true ie, p
then return the value of memcpy(p, s, len)
else return NULL
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.