Sanity check - making a static initializer constant

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



I am writing a parsing module that uses a bunch of POSIX regular
expressions.  I've grouped them together as follows, so that I can
conveniently compile/free them together:

  struct regex {
	int cflags;
	const char *pattern;
	regex_t regex;
	regmatch_t *const matches;
	size_t nmatch;
  };

  static const char foo_pattern[] = "foo";
  static regmatch_t foo_matches[1];

  /* More patterns and match arrays go here */

  static struct regex regexes[] = {
	{
		.cflags		= 0,
		.pattern	= "foo",
		.matches	= foo_matches,
		.nmatch		= 1,
	},
	/* Array members referencing additional patterns go here */
  };

When the time comes to actually make use of the regexes, I use static
constant pointers to refer to the compiled expressions and their
associated data:

  int match_foo(const char *s)
  {
	static const struct regex *const regex = &regexes[0];
	// static regmatch_t *const matches = regex->matches;
	// static regmatch_t *const matches = regexes[0].matches;
	static regmatch_t *const matches = foo_matches;

	return regexec(&regex->regex, s, regex->nmatch, matches, 0);
  }

Note the two commented-out initializers for "matches".  I would much
prefer to write the initializer in terms of the "regex" pointer or the
array.  This would make the connection much clearer and make any future
changes to the code much less error-prone.  Unfortunately, neither of
the commented-out initializers works; gcc (rightly) complains that the
initializer elements is not constant.

I cannot make the array itself constant, because of the need to compile
and free the "regex" members.

As far as I know, my options are:

1.  Live with the current scheme.

2.  Change "matches" in the function to an automatic variable.

3.  Change the "regex" member of "struct regex" to a pointer and
    create separate foo_regex, bar_regex, etc. objects.  I could then
    make the "regexes" array constant.

Am I missing anything?

Thanks!

-- 
========================================================================
Ian Pilcher                                         arequipeno@xxxxxxxxx
Sometimes there's nothing left to do but crash and burn...or die trying.
========================================================================




[Index of Archives]     [Linux C Programming]     [Linux Kernel]     [eCos]     [Fedora Development]     [Fedora Announce]     [Autoconf]     [The DWARVES Debugging Tools]     [Yosemite Campsites]     [Yosemite News]     [Linux GCC]

  Powered by Linux