473,664 Members | 2,773 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Static Variable Must Be Constant?

I want to initialize a static variable to a "random" value like:

static void *
get_key(struct dnsreq *req)
{
static uint16_t next_txnid = (uint32_t)req & 0xFFFF;

But gcc gives me an error:

src/dns.c: In function `get_key':
src/dns.c:173: initializer element is not constant

So a static initializer must be a constant?

Must I do:

static uint16_t next_txnid = 0;

if (!next_txnid) {
(uint32_t)req & 0xFFFF;
}

?

Thanks,
Mike
Nov 14 '05 #1
6 3890
Michael B Allen wrote:
I want to initialize a static variable to a "random" value like:

static void *
get_key(struct dnsreq *req)
{
static uint16_t next_txnid = (uint32_t)req & 0xFFFF;


You can't INITIALIZE a static variable with an expression that isn't a
constant expression. But you are free to ASSIGN to a static variable
with a variable or constant expression.

do this:

static uint16_t next_txnid; /* compiler will initialize to zero */
next_txnid = (uint32_t)req & 0xFFFF; /* you assign something to it */
INITALIZATIONS are for STARTING VALUES. Since static variables START
before a program begins, the initial values for static variables must
not depend on variables (like req) whose values can't be determined
before program start. Thus, your compiler needs to know what your
static variable's value will be before program start, which obviously
can't be a variable expression. In your case, does it matter what the
value of next_txnid is at program start? Most likely no.

Nov 14 '05 #2
Michael B Allen wrote:
I want to initialize a static variable to a "random" value like:

static void *
get_key(struct dnsreq *req)
{
static uint16_t next_txnid = (uint32_t)req & 0xFFFF;

But gcc gives me an error:

src/dns.c: In function `get_key':
src/dns.c:173: initializer element is not constant

So a static initializer must be a constant?


Yes.

But the question is, since you overwrite the value immediately
on each function call entry, why do you need the variable to
have static duration in the first place?

If you're just trying to save stack allocation overhead for
a specific implementation, then just do...

static uint16_t next_txnid;
next_txnid = req & 0xFFFFu;

--
Peter

Nov 14 '05 #3
Michael B Allen wrote:

So a static initializer must be a constant?

Of course, initializers are computed during compile time
Must I do:

static uint16_t next_txnid = 0;

if (!next_txnid) {
(uint32_t)req & 0xFFFF;
}


Just separate declaration and assignment:

static uint16_t next_txnid;
next_txnid = (uint32_t)req & 0xFFFF;

Nov 14 '05 #4
On Tue, 08 Feb 2005 17:40:59 -0500, Kenneth Bull wrote:
INITALIZATIONS are for STARTING VALUES. Since static variables START
before a program begins, the initial values for static variables must
not depend on variables


Good explaination. Thanks.

Mike
Nov 14 '05 #5
On Tue, 08 Feb 2005 17:22:58 -0500, Michael B Allen wrote:
I want to initialize a static variable to a "random" value like:

static void *
get_key(struct dnsreq *req)
{
static uint16_t next_txnid = (uint32_t)req & 0xFFFF;

But gcc gives me an error:

src/dns.c: In function `get_key':
src/dns.c:173: initializer element is not constant

So a static initializer must be a constant?
Yes, static variables are initialised once at program startup. So in your
example code next_txnid would *not* be initialised when the function is
called, only at program startup when the variable req doesn't exist.
Must I do:

static uint16_t next_txnid = 0;

if (!next_txnid) {
(uint32_t)req & 0xFFFF;
I assume you mean

next_txnid = (uint32_t)req & 0xFFFF;
}
}


So it appears that you want the one-off initialisation behaviour but at
the first time get_key() is called. If so then, yes, this is a reasonable
approach assuming of course that (uint32_t)req & 0xFFFF can't be zero. A
more exact approach would use a separate flag variable indicating whether
next_txnid had been initialised or not.

Lawrence
Nov 14 '05 #6
Michael B Allen wrote:
...
So a static initializer must be a constant?
Yes.
Must I do:

static uint16_t next_txnid = 0;

if (!next_txnid) {
(uint32_t)req & 0xFFFF;
Did you mean
next_txnid = (uint32_t)req & 0xFFFF;
}

?
...


Yes, that's one way to do it, provided '0' is not one of the possible
results of '(uint32_t)req & 0xFFFF'. If it is, you might end up with
"initialization s" that don't register a such, i.e. the variable will be
"re-initialized" again every time you go through this code.

Otherwise, if there's no definitive reserved "impossible " value among
the results of '(uint32_t)req & 0xFFFF' expression, you'll have no other
choice but to create another variable just to serve as a boolean
"already initialized" flag.

--
Best regards,
Andrey Tarasevich
Nov 14 '05 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
28195
by: Marcin Vorbrodt | last post by:
So I have a class Math that looks like this: Math { public: static Real PI(void); }; Real Math::PI(void) { return 4.0 * atan(1.0); }
4
5419
by: cppsks | last post by:
"Defining static const variables inside the class is not universally supported yet, so for now I guess you'll have to move the definition out of the body of the class. No, static const inside classes is only allowed for integral consts, like static const enum and static const int, not for arrays and structs. It does make sense for an array of integral consts though." I read the above statements in this group a while back. First off,...
9
3237
by: cppsks | last post by:
Taking the address of a static const resulted in a unresolved symbol. Why is that? Is the address assigned at load time? Thanks.
2
2635
by: Rafe Culpin | last post by:
Does anyone please know of a way to access static methods of a class, when the name of that class is held in a variable? I have several classes (PHP5) which all have identically named methods and members. I want to pass the name of one of the classes to an included file which does some standard operations using those methods and members. (So several different programs can include that file, each passing a different class name.)
10
4192
by: n.torrey.pines | last post by:
Are global variables (and const's) guaranteed to be initialized before static class members (and methods) ? const int x = 19907; int get_x() { return x; } // another compilation unit: int get_x();
3
5845
by: Steve Folly | last post by:
Hi, I had a problem in my code recently which turned out to be the 'the "static initialization order fiasco"' problem (<http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.12>) The FAQ section describes a solution using methods returning references to static objects. But consider:
9
8883
by: Jess | last post by:
Hello, I was told that if I declare a static class constant like this: class A{ static const int x = 10; }; then the above statement is a declaration rather than a definition. As I've *defined* "x"'s value to be 10, isn't above statement a
15
7854
by: akomiakov | last post by:
Is there a technical reason why one can't initialize a cost static non- integral data member in a class?
8
5704
by: aarklon | last post by:
Hi all, see:- http://linuxgazette.net/issue51/pramode.html
0
8348
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8863
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8779
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8636
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6187
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5660
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
2765
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2004
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1761
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.