1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | #include <stdio.h> struct integers { union { const int x = 0; int y; }; }; int main() { integers ints; ints.y = 1; // Prints "integer x = 1 | integer y = 1" printf("integer x = %d | integer y = %d", ints.x, ints.y); return 0; } |
1 2 3 4 5 6 7 8 9 10 11 12 | void f(int* y) { *y = 1; } const int x = 123; int main() { const int* ptr = &x; f((int*)ptr); } |
1 2 3 4 5 | int main() { char* str = "abcdef"; str[0] = 'm'; } |
Great... I'll stick with "static" instead of "inline".You should use whatever matches your intention. :)
Also using const can help the compiler generate better code.While I'm all pro-const, I've never seen this to be true.
If the function takes a const pointer the compiler will know that the values in that struct cannot have changed so he doesn't have to read them from memory again.You are confusing const with restrict keyword. Const doesn't guarantee this, because data of structure may alias with memory buffer that is changed by different pointers. Here's an example:
1 2 3 4 5 6 7 8 9 10 11 12 13 | struct S { int x; }; int f(const struct S* s, int* x) { int y = s->x; // reading from structure *x = 42; int z = s->x; // reading again from structure, can not reuse y value return y + x; } S s = { 5 }; f(&s, &s.x); |
1 2 3 4 5 6 | movl 4(%esp), %edx movl 8(%esp), %ecx movl (%edx), %eax // reading from structure pointer movl $42, (%ecx) // putting 42 with to *x addl (%edx), %eax // reading from structure pointer again (and adding to previous) ret |
1 2 3 4 5 6 7 | int f( const struct S* __restrict s, int* __restrict x) { int y = s->x; *x = 42; int z = s->x; return y + z; } |
1 2 3 4 5 6 | movl 4(%esp), %eax movl 8(%esp), %edx movl (%eax), %eax // reading from structure pointer movl $42, (%edx) // putting 42 with to *x addl %eax, %eax // this time reuse value read from structure before ret |
1 2 3 4 5 6 7 8 9 10 11 | struct S { int x; } void function( const S *s ); S s; s.x = 123; function( &s ); int y = s.x; // With const the compiler can assume that s.x is still 123 and // doesn't need to load the value from memory when accessing s.x |
owensd
You cannot make that claim at all. What if function() created a thread that delayed execution of the code that used the pointer to the struct? What's the value of s.x when the code in the thread executes?