Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

const struct declaration

Can someone tell me the difference between these two versions of a declaration of a structure?

struct S
{
  uint8_t a;
};

and

const struct S
{
  uint8_t a;
}

Followed by:

void main(void)
{
  struct S s = {1};
  s.a++;
}

Hint, i've tried both versions for S in Visual Studio C++ 2010 Express so I know that both compile with errors.

Is the "const struct" doing nothing at all? "const struct S s = {1};" certainly does, but that's not the issue at the moment.

Regards Rich

/********************************************/

I've just worked out what

const struct <typename> <{type}> <variable instances a, b, .., z>;

is doing:

When const is present before the "struct", all variable instances are const, as though they'd be defined with:

const struct <typename> a, b, z;

So it does do something, but not when there's no instance definitions in-line with the struct declaration.

Rich

like image 343
4 revs, 4 users 79% Avatar asked Dec 07 '22 19:12

4 revs, 4 users 79%


2 Answers

A declaration of structure just defines the data type.

const qualifier appies to a variable not a data type. So adding const preceeding a struct declaration should be redundant at the most.

like image 170
Alok Save Avatar answered Dec 09 '22 07:12

Alok Save


With:

const struct S
{
  uint8_t a;
};

The const qualifier there is nonsense, and may even cause a compilation error with some C compilers. gcc issues a warning.

The intent appears to be to declare the data type struct S. In this case, the proper syntax is:

struct S
{
  uint8_t a;
};
like image 45
Daniel Trebbien Avatar answered Dec 09 '22 08:12

Daniel Trebbien