开发者

difference between static T const and static const T

开发者 https://www.devze.com 2023-02-03 14:46 出处:网络
Assuming that T is an arbitrary type and we\'re talking about Objective-C. Then what is the difference be开发者_开发问答tween

Assuming that T is an arbitrary type and we're talking about Objective-C. Then what is the difference be开发者_开发问答tween

static T const x = ....

and

static const T x = ....

?


They are the same.


A little background about const:

Objective-C, just like C, uses the Clockwise/Spiral Rule. In a case where you have only modifiers at the left side of the variable (of foo) you read stuff going from right to left:

int * const * var;

is read: var is a pointer to a constant pointer to integer.

However const has the same effect when it's before or after the first type:

int const var; // constant integer
const int var; // constant integer, same as above

static, instead, affects the whole variable: it's the variable to be static, not the element pointed by it or anything else: a pointer to integer can be used both to point to a static integer, or to an automatic integer without distinction, and C doesn't provide a syntax to declare a pointer able to point to static variables (or to automatic variables) only.

static int * x; // x is a static pointer to integer
int static * y; // as above y is a static pointer to integer
int * static z; // THIS SYNTAX IS NOT ALLOWED
                // but if it was, it would mean the same thing

For this reason I prefer to place it before any const modifier, but it doesn't actually matter.

static  const int * const * x; // this is what I do


I believe the distinction is only important for pointer types; for example 'char *'.

const char *p means that the buffer pointed to by p cannot be updated but pointer p itself can be changed (typically incremented with p++), for example:

void f(const char *p)
{
    while (*p != '\0')
    {
        putc(*p);
        p++;
    }
}

char * const p means that the buffer pointed to by p can be updated but pointer p cannot be changed.

EDIT Thanks for JeremyP for the following comment:

It's quite common in Apple's APIs to define string constants (instead of using #defines), especially if the string is an NSString i.e. NSString * const kFoo = @"bar";

0

精彩评论

暂无评论...
验证码 换一张
取 消