代码之家  ›  专栏  ›  技术社区  ›  Ande Turner

C: `const `关键字的行为

  •  7
  • Ande Turner  · 技术社区  · 16 年前

    const

    在Java中,最终初始化必须在声明时进行,但通过ANSI C实现,我可以初始化一个 常量

    7 回复  |  直到 6 年前
        1
  •  9
  •   Pete Kirkham    16 年前

    Java编译器有少量的流逻辑,允许您初始化 final 声明后的变量。这是合法的Java:

    final int something;
    
    if ( today == Friday )
        something = 7;
    else
        something = 42;
    

    final int something;
    
    if ( today == Friday )
        something = 7;
    
    if ( today != Friday )
        something = 42;
    

    在ANSI C89中, const extern

    const int something = ( today == Friday ) ? 7 : 42;
    

    常量

    #include<stdio.h>
    
    int main ( void )
    {
        printf ( "wibble\n" );
    
        {
            const int x = 10;
    
            printf ( "x = %d\n", x );
        }
    
        return 0;
    }
    
        2
  •  3
  •   YeahStu    6 年前

    C89 ,您通常可以通过引入一个裸块来增加额外的作用域,从而使定义更接近首次使用的点。之前:

    int a, b, c;
    
    a = 12;
    // Do some stuff with a
    
    b = 17;
    // Do some stuff with a and b
    
    c = 23;
    // Do some stuff with a, b, and c
    

    int a = 12;
    // Do some stuff with a
    {
        int b = 17
        // Do some stuff with a and b
        {
            int c = 23;
            // Do some stuff with a, b and c
        }
    }
    

    C99 当然,您可以定义块开头以外的变量:

    int a = 12;
    // Do some stuff with a
    
    int b = 17
    // Do some stuff with a and b
    
    int c = 23;
    // Do some stuff with a, b and c
    
        3
  •  3
  •   Peter Mortensen Pieter Jan Bonestroo    6 年前

    const

    error: assignment of read-only variable 'foo'

    const int foo;
    foo = 4;
    

    const指针也是如此(注意: const int *

    int * const foo;
    foo = 4;
    
        4
  •  2
  •   R.. GitHub STOP HELPING ICE    16 年前

    • 函数参数中的指针(或基于参数的局部变量指针),其中函数遵守不修改所指向数据的约定。const关键字有助于确保函数实现尊重不修改的要求(它需要特殊的努力转换来摆脱const),并允许这一要求通过多个函数调用传播。

        5
  •  2
  •   Peter Mortensen Pieter Jan Bonestroo    6 年前

    void func()
    {
        int y;
    
        // Do assertions
        assert(something);
        {
            int const x = 5;
            // Function body
         }
    }
    
        6
  •  1
  •   Peter Mortensen Pieter Jan Bonestroo    6 年前

    const int x = 2;
    

    const int x;
    
    x = 2;
    

    如果我是你,我会尽力确保我理解你描述的编码规则的意图。我怀疑理智的编码规则会阻止初始化变量(即使是非常量变量)。

    const int * p;
    

    常量变量的声明。它是一个指向const int的非const指针变量的声明。

    extern const int x;
    

    但是在执行代码、断言检查等之后,您仍然无法初始化x。

        7
  •  0
  •   Peter Mortensen Pieter Jan Bonestroo    6 年前

    如果你想抛弃const LHS

    const int n = 0;
    
    *((int*)&n) = 23;
    
    推荐文章