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

Re: weird strncmp usage?

From
Johannes Schindelin <johannes.schindelin@gmx.de>
Date
Nov 2, 2006, 09:15 UTC
Message-ID
<Pine.LNX.4.63.0611021008180.1670@wbgn013.biozentrum.uni-wuerzburg.de>
In-Reply-To
<20061102065127.GA23105@coredump.intra.peff.net>
Hi,
On Thu, 2 Nov 2006, Jeff King wrote:
Show 13 quoted lines
> On Thu, Nov 02, 2006 at 01:44:36AM +0000, Andy Whitcroft wrote:
> 
> > That said if you know its constant you can also use sizeof("foo") and
> > that is done at compile time.  Something like:
> > 
> > #define strxcmp(x, y)	strncmp((x), (y), sizeof((y))
> 
> You would, of course, need to use sizeof(y)-1 to avoid comparing the NUL
> termination. :)
> 
> This is a slightly dangerous macro, because it _only_ works for string
> literals, but not pointers (which is fine in this case, but its
> limitations need to be documented).
It would be even better to avoid these errors by doing something like
	#define starts_with(x, y) !strncmp((x), #y, sizeof(#y) - 1)
which would be used like this:
	if (starts_with(arg, --abbrev=))

However, in this case, you would need another macro, which automatically extracts the argument, and soon you will end up with yet another getopt package.

Ciao, Dscho

Previous: Jeff KingNext: Han-Wen Nienhuys
Message 4 of 7 in “weird strncmp usage?”
  1. Han-Wen NienhuysNov 2, 2006
  2. Andy WhitcroftNov 2, 2006
  3. Jeff KingNov 2, 2006
  4. Johannes SchindelinNov 2, 2006
  5. Han-Wen NienhuysNov 2, 2006
  6. Petr BaudisNov 2, 2006
  7. Florian WeimerNov 3, 2006

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.