Reputation: 4199
Is the statement below a kind of shorthand? i need someone help me understand with it.
#define clean_errno()(errno == 0? "None": strerror(errno))
From the execution result, I guess it means once I confront clean_errno()
,if errno ==0
, I replace clearn_errno()
with None
, if not, I replace clean__errno()
with strerror(errno)
. but I don't know how to analyse this statement logically?
Upvotes: 0
Views: 404
Reputation: 409442
Preprocessor macros are replaced in their call-sites.
That means a statement like
printf("Error = %s\n", clean_errno());
will be replaced by
printf("Error = %s\n", (errno == 0? "None": strerror(errno)));
That will then at run-time print either "None"
if errno == 0
, otherwise print the result of strerror(errno)
.
As for the ?:
expression itself, it is the conditional (a.k.a. the ternary) expression, and it works similar to a if-else
.
However, using a macro like this is not something I would recommend, as the value of errno
is usually undefined if a function doesn't fail. You need to make sure the previous function actually did fail before checking errno
, in which case it will never be zero. There are very few places where errno
will be reset to zero unless you specifically do it beforehand and know that the function you call will not modify it unless there's an error.
Upvotes: 6
Reputation: 19221
The code is evaluated during runtime and follows the shorthand:
condition ? if_true : if_false
This shorthand is very similar to a regular if else
statement.
However, unlike normal if else
in C, the shorthand can be used as an expression as well as a statement. i.e.:
char * str = 1 ? "true" : "false";
... which doesn't work so well with if else
(char * str = if ...
probably wouldn't work).
Try it with 0 ? "true" : "false"
and test it out.
Good luck!
Upvotes: 2