原文:http://www.noxeos.com/2011/07/29/c-const-static-keywords/

C: const and static keywords

Ok, once and for all, I’ll try to clarify to meaning of the ‘const’ and ‘static’ keywords in C (it applies to Objective-C and C++ too).

I’m just tired of questions about this on StackOverflow.

Objective-C programmers usually don’t think about C code while coding. I personally think this is a big mistake (it can sometimes apply to C++ programmers too).

Objective-C is just a layer over C. So in order to be a good Objective-C programmer, you HAVE to know at least a few things about the C language.

I don’t know why C has such a bad reputation for Objective-C coders, especially on iOS. And it’s very surprising to see the lack of knowledge of some Objective-C developers.

So once and for all:

If you want to code in Objective-C, learn at least the following C topics:

  • Language keywords and their meanings
  • Pointers and pointer arithmetic
  • C standard library

Those are the (very) basics.

Objective-C is a very nice object-oriented language, with amazing runtime capabilities. That’s true.
But it doesn’t mean you can bypass completely the C language.
A lot of time, you’ll save a lot of processor time and memory, just by knowing a few things about the C language, rather than relying on the apparent simplicity of the Objective-C language.

But that’s a different story. Now back on our keywords…

const

First of all, the ‘const’ keyword.

Ok, it means ‘constant’… So:

const int x = 42;

declares a constant integer variable. It means it’s value can’t be modified. It’s value is initially assigned to 42.
If you try to change its value later, the compiler will issue a warning, or an error, depending on your compiler settings.
So the following statement is invalid:

const int x = 42;
x = 43;

That’s pretty easy to understand.
The problem comes with pointers.

Let’s take a look at the following code:

char * str = "hello, world";

It declares a ‘char’ pointer. Ok… But then what about this:

char * const str = "hello, world";

or

const char * str = "hello, world";

Now read carefully.
The first one declares a constant pointer to a char.

It means the the characters of the string can be modified, but not the pointer value.
So the variable ‘str’ cannot be assigned to another pointer.

For instance, this is invalid:

char * hello = "hello, universe";
char * const str = "hello, world";
str = hello;

as your a modifying the pointer value (not the string value).

This is valid:

char * const str = strdup( "hello, world" );
str[ 0 ] = 'a';

The ‘str’ variable will then contain ‘hello, world’. Remember: the pointer can’t be modified, the value that is pointed can be.

It’s the exact opposite with the following notation:

const char * str = "hello, world";

Here, you can assign the pointer to another variable, but you can’t change the value.

The ‘const’ keyword is contextual, in a way, when using pointers. It can apply to the pointer itself, or to the value pointed.

So, in order to resume:

const int * x;

A modifiable pointer to a constant integer.

int * const x;

A constant pointer to an modifiable integer.

const int * const x;

A constant pointer to a constant integer.

static

The static keyword can have two meanings.

First of all, it can be declared inside a function.
Let's take a look at this example:

#include <stdio.h>

void foo( void );
void bar( void );

void foo( void )
{
int x = 0;

printf( "X - foo: %i\n", x );

x++;
}

void bar( void )
{
static int x = 0;

printf( "X - bar: %i\n", x );

x++;
}

int main( void )
{
foo();
foo();
foo();
bar();
bar();
bar();

return 0;
}

The output will be:

X - foo: 0
X - foo: 0
X - foo: 0
X - bar: 0
X - bar: 1
X - bar: 2

Because a simple local variable, as in the 'foo' function, only exists when the function is called. It's destroyed (to be simple) when the function exits.

So for the 'foo' function, the variable is created each time the function is called, with a value of '0'. The value is printed, then incremented.
The function then exit, and the variable is destroyed.

But in the 'bar' function, the variable is declared as static. It means the value will persist across function calls.
It's initialized the first time the function is called, but only at that time. Once it has been initialized, it just exist, so its value will be taken for the next function calls.

Now the 'static' keyword as a completely different meaning when used in a variable declared outside of a function (in the global scope).

It means that the variable will be «file scoped». In other words, the variable, which is global, will be accessible only from the scope of the file which declared it. It won't be accessible from other files.

It's just a way to create global private variable.

For instance, imagine a file called 'foo.c':

int x = 42;
static int y = 42;

From a 'bar.c' file, you'll be able to access the 'x' symbol, if both files are linked together. But you won't be able to access the 'y' symbol, as it's decaled as 'static'.
It means that the symbol for the 'y' variable won't be exported by the linker, when the symbol for the 'x' variable will be.

In other words, you'll be able to access the 'y' global variable only from function declared in the 'foo.c' file. The 'x' variable will be also accessible from other files.

Of course, the 'static' keyword can be combined with const.
For instance:

static const int * const y;

A constant pointer to a constant integer, that will be accessible only from the file which declared it.

C: const and static keywords的更多相关文章

  1. const extern static 终极指南

    const extern static 终极指南 不管是从事哪种语言的开发工作,const extern static 这三个关键字的用法和原理都是我们必须明白的.本文将对此做出非常详细的讲解. co ...

  2. const、static和extern的正确使用方式

    我们在看一些大牛的第三方时,里面会出现很多const.static和extern,尤其是const和static,const和extern的结合使用,直接令很多小伙伴懵逼了,今天就详细讲解一下这三个关 ...

  3. 《OOC》笔记(1)——C语言const、static和extern的用法

    <OOC>笔记(1)——C语言const.static和extern的用法 C语言中const关键字用法不少,我只喜欢两种用法.一是用于修饰函数形参,二是用于修饰全局变量和局部变量. 用c ...

  4. 到底是 const 还是 static readonly

    真的一样? const 和 static readonly 常在程序中用来声明常量,调用方法也没有什么不同,他们真的一样吗?我们可以做个试验. 程序集内的常量 现在我们建立一个程序,里面有一个MyCl ...

  5. 【转】const和static readonly

    我们都知道,const和static readonly的确很像:通过类名而不是对象名进行访问,在程序中只读等等.在多数情况下可以混用.二者本质的区别在于,const的值是在编译期间确定的,因此只能在声 ...

  6. (C#) What is the difference between "const" and "static readonly" ?

    const int a must be initialized initialization must be at compile time readonly int a can use defaul ...

  7. (转) C++ static、const和static const 以及它们的初始化

    const定义的常量在超出其作用域之后其空间会被释放,而static定义的静态常量在函数执行后不会释放其存储空间. static表示的是静态的.类的静态成员函数.静态成员变量是和类相关的,而不是和类的 ...

  8. C# const与static的理解

    C#  const与static的理解 static readonly与 const变量,作用是一样的,无论访问修饰符是不是public,还是其它(private. protected.interna ...

  9. c#中const、static、readonly的区别

    1. const与readonly const ,其修饰的字段只能在自身声明时初始化. Readonly 是只读变量,属于运行时变量,可以在类初始化的时候改变它的值.该类型的字段,可以在声明或构造函数 ...

随机推荐

  1. WindowsServer2012桌面图标设置

    1.win+R调出运行窗口 2.输入:rundll32.exe shell32.dll,Control_RunDLL desk.cpl,,0 即可

  2. 高效的INSERT INTO SELECT和SELECT INTO

    1.INSERT INTO SELECT,目标表必须存在,才可批量插入 INSERT INTO 目标表Table(field1,field2,field2,...) SELECT value1,val ...

  3. WCF的传输安全(读书笔记)

    Wcf的传输安全主要涉及认证.消息的一致性和机密性.Wcf采用两种不同的机制来解决这三个涉及传输安全的问题,即Transport安全模式和Message安全模式. Transport安全模式利用基于传 ...

  4. ArchLinux 下架设PPTPD VPN服务

    直接上命令吧: 安装: pacman -Sy pacman -S pptpd 配置: vim /etc/pptpd.conf option /etc/ppp/options.pptpd stimeou ...

  5. windows8 平板的使用心得

    一.问题的提出 买了本windows8 平板,全触摸,不带键盘鼠标,第一次用.系统与之前版本有差别,不适应. 二.问题的分析 总是有地方改善. 三.问题的解决 1.我的电脑,要在桌面上显示. 点桌面, ...

  6. linux中mysql密码找回的两种方式

    方法一:修改my.cnf配置文件 1.首先确认服务器出于安全的状态,也就是没有人能够任意地连接MySQL数据库. 因为在重新设置MySQL的root密码的期间,MySQL数据库完全出于没有密码保护的  ...

  7. andriod手机签到应用服务器设计

    最近导师要求我和另一个同学开发一个手机上课签到应用,我负责客户端和服务器之间的通信架构编写和数据的存储 本人大学四年只用过汇编和C/C++,因此对andriod开发还是一窍不通,花了一个星期写出来了基 ...

  8. 红黑树(二)之 C语言的实现

    概要 红黑树在日常的使用中比较常用,例如Java的TreeMap和TreeSet,C++的STL,以及Linux内核中都有用到.之前写过一篇文章专门介绍红黑树的理论知识,本文将给出红黑数的C语言的实现 ...

  9. HMM 自学教程(八)总结

    本系列文章摘自 52nlp(我爱自然语言处理: http://www.52nlp.cn/),原文链接在HMM 学习最佳范例,这是针对国外网站上一个 HMM 教程的翻译,作者功底很深,翻译得很精彩,且在 ...

  10. Robot Framework自动化测试(四)--- 分层思想

    谈到Robot  Framework 分层的思想,就不得不提“关键字驱动”. 关键字驱动: 通过调用的关键字不同,从而引起测试结果的不同. 在上一节的selenium API 中所介绍的方法其实就是关 ...