This is the mail archive of the
gcc-help@gcc.gnu.org
mailing list for the GCC project.
Sanity check - making a static initializer constant
- From: Ian Pilcher <arequipeno at gmail dot com>
- To: gcc-help at gcc dot gnu dot org
- Date: Wed, 09 Oct 2013 14:10:39 -0500
- Subject: Sanity check - making a static initializer constant
- Authentication-results: sourceware.org; auth=none
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 = ®exes[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(®ex->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@gmail.com
Sometimes there's nothing left to do but crash and burn...or die trying.
========================================================================