C:在`const`关键字的行为 [英] C: Behaviour of the `const` keyword

查看:131
本文介绍了C:在`const`关键字的行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经被告知,如果我在ANSI-C编码我在这两个变量将使用顺序声明,断言指针不为空,并且指标是范围内,并使用情况之前只初始化变量。

I've been told that if I'm coding in ANSI-C to declare in the order that the variables will be used, assert that pointers are not null and that indices are within bounds, and to initialize just before usage of the variable.

如果我宣布一个const我可以断言和code块后初始化?
在Java中最后的初始化必须发生在声明的,但它是通过ANSI-C实现一致的,我可以在申报的时候?

If I declare a const can I initialize it after a block of assertions and code ? In Java final initializations must occur at declaration, yet is it consistent through ANSI-C implementations that I can initialize a const once but not necessarily at the time of declaration ?

推荐答案

Java编译器有少量流逻辑的,让你自己的声明之后initalise 最后变量。这是合法的Java:

The Java compiler has a small amount of flow logic to allow you to initalise final variables after their declaration. This is legal Java:

final int something;

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

如果任何分支机构离开未定义终值Java将检测。它不会分析的条件,所以这是不合法的Java,即使它的逻​​辑类似:

Java will detect if any branches leave the final value undefined. It won't analyse the conditions, so this is not legal Java, even though it's logically similar:

final int something;

if ( today == Friday )
    something = 7;

if ( today != Friday )
    something = 42;

在ANSI C89,常量变量(除的extern )必须在语句中初始化它们宣布

In ANSI C89, const variables ( other than extern ) must be initialised in the statement they are declared in.

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

的extern 上的声明修饰符告诉该变量在不同的complation单元(在此编译单元或其他地方)初始化编译器。

The extern modifier on a declaration tells the compiler that the variable is initialised in a different complation unit ( or elsewhere in this compilation unit ).

在ANSI C99,可以混合声明和code,所以你可以声明并断言和code块后初始化一个常量变量。 1999 ANSI C便携性仍然是一个问题。

In ANSI C99, you can mix declarations and code, so you can declare and initialise a const variable after a block of assertions and code. Portability of 1999 ANSI C remains an issue.

一个用于C89的解决办法是要注意,在块范围而不是函数范围内声明preceding code的工作规则,所以你可以这样做:

A work around for C89 is to note that the rules for declarations preceding code work at block scope rather than function scope, so you can do this:

#include<stdio.h>

int main ( void )
{
    printf ( "wibble\n" );

    {
        const int x = 10;

        printf ( "x = %d\n", x );
    }

    return 0;
}

这篇关于C:在`const`关键字的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆