git/list[1] front-page[2] threads[3] people[4] search[5] about
 

[PATCH 1/5] git-compat-util: add xstrdup_or_null helper

From
Jeff King <peff@peff.net>
Date
Jan 13, 2015, 01:57 UTC
Message-ID
<20150113015736.GA18986@peff.net>
In-Reply-To
<20150113015427.GA5497@peff.net>

It's a common idiom to duplicate a string if it is non-NULL, or pass a literal NULL through. This is already a one-liner in C, but you do have to repeat the name of the string twice. So if there's a function call, you must write:

  const char *x = some_fun(...);
  return x ? xstrdup(x) : NULL;
instead of (with this patch) just:
  return xstrdup_or_null(some_fun(...));
Signed-off-by: Jeff King <peff@peff.net>
---
This example is the heart of the readability question to me. It is nice
to avoid the temporary, which makes the code more direct. But it also
sticks some_fun(...) inside another function, which is a little harder
to read.
 git-compat-util.h | 5 +++++
 1 file changed, 5 insertions(+)
diff --git a/git-compat-util.h b/git-compat-util.h
index dcecd85..8157eb2 100644
--- a/git-compat-util.h
+++ b/git-compat-util.h
@@ -675,6 +675,11 @@ extern char *xgetcwd(void);
 
 #define REALLOC_ARRAY(x, alloc) (x) = xrealloc((x), (alloc) * sizeof(*(x)))
 
+static inline char *xstrdup_or_null(const char *str)
+{
+	return str ? xstrdup(str) : NULL;
+}
+
 static inline size_t xsize_t(off_t len)
 {
 	if (len > (size_t) len)
-- 
2.2.1.425.g441bb3c
Previous: Jeff KingNext: Jonathan Nieder
Message 8 of 19 in “blame.c: fix garbled error message”
  1. blame.c: fix garbled error messageLukas Fleischer, Jan 10, 2015
  2. Junio C HamanoJan 12, 2015
  3. Jeff KingJan 12, 2015
  4. Junio C HamanoJan 12, 2015
  5. Jeff KingJan 12, 2015
  6. Junio C HamanoJan 13, 2015
  7. Jeff KingJan 13, 2015
  8. 1/5 git-compat-util: add xstrdup_or_null helperJeff King, Jan 13, 2015
  9. Jonathan NiederJan 13, 2015
  10. Jeff KingJan 13, 2015
  11. 2/5 builtin/apply.c: use xstrdup_or_null instead of null_strdupJeff King, Jan 13, 2015
  12. 3/5 builtin/commit.c: use xstrdup_or_null instead of envdupJeff King, Jan 13, 2015
  13. 4/5 use xstrdup_or_null to replace ternary conditionalsJeff King, Jan 13, 2015
  14. 5/5 blame.c: fix garbled error messageJeff King, Jan 13, 2015
  15. Lukas FleischerJan 14, 2015
  16. Junio C HamanoJan 14, 2015
  17. Jeff KingJan 14, 2015
  18. Junio C HamanoJan 14, 2015
  19. Lukas FleischerJan 12, 2015

Read the whole thread, see it on lore, or plain text.

$ cat FOOTERMessages come from the public archive at lore.kernel.org/git, fetched every hour. The front page is chosen and written each morning by an AI editor and can be wrong; the threads themselves are the record. About and API. For agents: an MCP server at https://gitlist.dev/mcp, and any thread, story or person page as Markdown by adding .md to its URL (or sending Accept: text/markdown). Details in /llms.txt.