source: doc/theses/mike_brooks_MMath/programs/bkgd-carray-decay.c @ 266732e

Last change on this file since 266732e was 266732e, checked in by Peter A. Buhr <pabuhr@…>, 5 months ago

switch to tabs, first attempt changing program-input style

  • Property mode set to 100644
File size: 1.4 KB
Line 
1#include <assert.h>
2int main() {
3        float a[10];                            $\C{// array}$
4        float (*pa)[10] = &a;           $\C{// pointer to array}$
5        float a0 = a[0];                        $\C{// element}$
6        float *pa0 = &(a[0]);           $\C{// pointer to element}$
7
8        float *pa0x = a;                        $\C{// (ok)}$
9        assert( pa0 == pa0x );
10        assert( sizeof(pa0x) != sizeof(a) );
11
12        void f( float x[10], float *y ) {
13                static_assert( sizeof(x) == sizeof(void*) );
14                static_assert( sizeof(y) == sizeof(void*) );
15        }
16        f(0,0);
17
18        // reusing local var `float a[10];`}
19        float v;
20        f(  a,  a ); $\C{// ok: two decays, one into an array spelling}$
21        f( &v, &v ); $\C{// ok: no decays; a non-array passes to an array spelling}$
22
23        char ca[] = "hello";    $\C{// array on stack, initialized from read-only data}$
24        char *cp = "hello";     $\C{// pointer to read-only data [decay here]}$
25        void edit(char c[]) {   $\C{// param is pointer}$
26                c[3] = 'p';
27        }
28        edit(ca);               $\C{// ok [decay here]}$
29        edit(cp);               $\C{// Segmentation fault}$
30        edit("hello");          $\C{// Segmentation fault [decay here]}$
31
32        void decay( float x[10] ) {
33                static_assert( sizeof(x) == sizeof(void*) );
34        }
35        static_assert( sizeof(a) == 10 * sizeof(float) );
36        decay(a);
37
38        void no_decay( float (*px)[10] ) {
39                static_assert( sizeof(*px) == 10 * sizeof(float) );
40        }
41        static_assert( sizeof(*pa) == 10 * sizeof(float) );
42        no_decay(pa);
43}
44
45// Local Variables: //
46// compile-command: "sed -f sedcmd bkgd-carray-decay.c > tmp.c; gcc tmp.c" //
47// End: //
Note: See TracBrowser for help on using the repository browser.