Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does a 'const struct' differ from a 'struct'?

Tags:

c

syntax

What does const struct mean? Is it different from struct?

like image 752
Manu Avatar asked Nov 24 '10 12:11

Manu


People also ask

Can a struct member be const?

You can const individual members of a struct. Declaring an entire instance of a struct with a const qualifier is the same as creating a special-purpose copy of the struct with all members specified as const .

What are the differences between a C++ struct and AC struct?

A C# struct is managed code, which will be freed by the C# garbage when nobody refers to it anymore. Its destructor is called whenever the garbage collector decides to clean it up. A C++ struct is an unmanaged object, which you have to clean up yourself.

What is the use of const keyword in C?

The const keyword specifies that a variable's value is constant and tells the compiler to prevent the programmer from modifying it. In C, constant values default to external linkage, so they can appear only in source files.

Can a struct have functions?

Can C++ struct have member functions? Yes, they can.


1 Answers

The const part really applies to the variable, not the structure itself.

e.g. @Andreas correctly says:

const struct {     int x;     int y; } foo = {10, 20}; foo.x = 5; //Error 

But the important thing is that variable foo is constant, not the struct definition itself. You could equally write that as:

struct apoint {     int x;     int y; };  const struct apoint foo = {10, 20}; foo.x = 5; // Error  struct apoint bar = {10, 20}; bar.x = 5; // Okay 
like image 56
GrahamS Avatar answered Sep 30 '22 13:09

GrahamS