Skip to main content
gamedev.net
🔒 Locked

Struct const member initialization

Started by CyberSlag5k Apr 24, 2004 at 12:49 PM 6 replies 2.4k views
Original Post
CyberSlag5k
CyberSlag5k
I have a C struct that I would like to store a const short int in. However, I get an error when I create an object saying I have uninitialized constant members. Is there a way I can initilize this value ahead of time or at least in the same line that I create the item in? I would love to just make it a short int but what I am storing is, in fact, a const short int (and it seems more than a little silly to me that my compiler is unable to convert between a short int and a const short int). Thank you When you find yourself in the company of a halfling and an ill-tempered Dragon, remember, you do not have to outrun the Dragon...
Without order nothing can exist - without chaos nothing can evolve.
Fruny
Fruny

int main()
{
struct foo
{
const int i;
};

struct foo f = { 25 };

printf("%d\n", f.i);

return 0;
}


Works for me.
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan
nonpop
nonpop

struct foo
{
foo (int const i) : m_i(i) {}
int const m_i;
};

foo f (7);

Should work, too

EDIT: Tried it and it DOES work.


[edited by - nonpop on April 24, 2004 2:23:28 PM]
TangentZ
TangentZ
quote:
Original post by nonpop
Should work, too

EDIT: Tried it and it DOES work.



The OP said "C struct".

I''ll bet the OP wanted a "C solution".



Kami no Itte ga ore ni zettai naru!
神はサイコロを振らない!
Aprosenf
Aprosenf
Correct me if I''m wrong, but isn''t the const identifier a C++ token? If the compiler doesn''t mind the const, then nonpop''s solution is perfectly valid.
SiCrane
SiCrane
I think the point was that C doesn''t recognize struct member functions including constructors. nonpop''s code is not valid C.
nonpop
nonpop
whoops...
But is const valid C then?
SiCrane
SiCrane
Yes, C has had const for quite some time now, though it works slightly different than C++''s const.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.