Question Details

No question body available.

Tags

c

Answers (2)

January 11, 2026 Score: 2 Rep: 411,463 Quality: Low Completeness: 40%

In the first example, bar is constant and you can not change its value once initialized.

In the second case bar itself is not constant, but the data it points to is.

So in the second case you can assign to bar anytime you like, but in the first case it's not possible.

That bar is a member inside a structure doesn't matter, it has the same semantics as for the same declarations anywhere else.

January 11, 2026 Score: 1 Rep: 391,519 Quality: Medium Completeness: 100%
  • const int bar aka int const bar means that bar is a constant int. Once initialized, the field can't be modified directly.
  • int const bar means that bar is a constant pointer to an int. Once initialized, the field can't be modified directly.
  • const int bar means that bar is a pointer to a constant int. bar isn't constant and can be modified. It's that to which bar points that's constant.

This is easy to check!

#include 

struct Foo { const int bar; // bar is a constant int };

int main( void ) { struct Foo foo = { 123 }; foo.bar = 456; // error: assignment of read-only member 'bar' printf( "%d\n", foo.bar ); }

const (type) var is just a more readable version of (type) var const. We can use spiral rule to explain it what it means.

Same thing:

#include 

struct Foo { int const bar; // bar is a constant int };

int main( void ) { struct Foo foo = { 123 }; foo.bar = 456; // error: assignment of read-only member 'bar' printf( "%d\n", foo.bar ); }

Changing to a pointer makes no difference:

#include 

struct Foo { int const bar; // bar is a constant pointer to an int };

int main( void ) { int i = 123; int j = 456; struct Foo foo = { &i }; foo.bar = &j; // error: assignment of read-only member 'bar'
( foo.bar ) = 789; // ok printf( "%d\n", ( foo.bar ) ); }

In your second snippet, it's not bar that's constant but
bar.

#include 

struct Foo { const int bar; // bar is a pointer to a constant int };

int main( void ) { int i = 123; int j = 456; struct Foo foo = { &i }; foo.bar = &j; // ok
( foo.bar ) = 789; // error: assignment of read-only location 'foo.bar' printf( "%d\n", ( foo.bar ) ); }