[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: -Wall does not like RCS stuff



Array names in expressions "decay" into pointers. It simplifies things
to treat arrays as pointers. We don't need a complicated mechanism top
treat them as a composite object, or suffer the inefficiency of copying
everything when passing them to a function. But don't make the mistake
of thinking arrays and pointers are always equivalent.
-- Peter Van Der Linden, Expert C Programming (Deep C secrets)

The combination of const and * is usually only used to simulate
call-by-value for array parameters.

const char a[] = "aaaaa"; /* read-only subscripted array reference
(contents are read-only) */
const char *p = "bbbbb"; /* read-only subscripted pointer reference
(contents are read-only)*/
p is changeable, a is NOT but that is not due the const keyword! It is
because it's an array.

Consider the following:
#include <stdio.h>

const char a[] = "aaaaa"; /* read-only subscripted array reference */
const char *p = "bbbbb"; /* read-only subscripted pointer reference */

int main(int argc, char **argv)
{
  printf("a: %s\n", a); /* a decays to pointer */
  printf("p: %s\n", p); /* p IS a pointer */

  p = a; /* not so read-only!! */
  /* a = p; incompatible types compiler halts + warning: assignment of
read-only variable `a' */
  /* remove upper line to compile */

  printf("new a: %s\n", a); /* p now points to a */
  printf("new p: %s\n", p); /* p now points to a */
  strcpy(p, a); /* compiler warns but allows it. will segfault.
read-only worked! */
  strcpy(a, "abcde"); /* compiler warns again. will segfault. read-only
worked! */
  a[1] = 's'; /* compiler warns and it will segfault */
  printf("new p: %s\n", p); /* will never reach this */

  return 0;
}

For what it's worth.
/marco
----- Original Message -----
From: "Peter Strömberg" <peters_(_at_)_telia_(_dot_)_net>
To: <tech_(_at_)_openbsd_(_dot_)_org>
Sent: Saturday, November 03, 2001 3:16 PM
Subject: Re: -Wall does not like RCS stuff


On 3 Nov 2001 at 15:06, Joe Abley wrote:

> ...
> I thought the definitions of a1 and a3 (and a2 and a4) were
> equivalent in ANSI C, but gcc is treating them differently wrt
> the "defined by not used" warnings.

That's because they are NOT equivalent.

static char *a1 = "foo";
static const char *a2 = "foo";
static char *const b1 = "foo";
static const char *const b2 = "foo";
static char a3[] = "foo";
static const char a4[] = "foo";

int main(void)
{
        return(0);
}

$ cc -Wall c.c
c.c:1: warning: `a1' defined but not used
c.c:2: warning: `a2' defined but not used
c.c:5: warning: `a3' defined but not used

a2 is a pointer to a constant string
b1 is a constant pointer to a string

/Peter