用自身初始化C ++ const变量 [英] Initialize C++ const variable with itself

查看:65
本文介绍了用自身初始化C ++ const变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在我遇到了以下类型的错误:

Just now I had a bug of the following sort:

#include <iostream>

const int i = i;

int main(void)
{
    /* not allowed by default, but with -fpermissive */
    //const int i;
    /* allowed by default, even without -fpermissive. Seems to initialize to 0 */
    for ( int j = 0; j < i; ++j )
        std::cout << "hi";
    /* i = 0 */
}

编译于:

g++ const-init.cpp -Wall -Wextra -pedantic -O2

因为编译器默默地将i初始化为0,所以优化了一些循环。该错误是由于复制粘贴错误引起的。

Because the compiler silently initialized i to 0 some loops were optimized away. The error happened because of a copy-paste error.

此功能是否有效和/或记录在某处?它甚至有什么用?它有名称吗?

Is this 'feature' valid and/or documented somewhere? What is it even good for? Does it have a name?

编辑:如果没有-O2,g ++的行为就像我希望的那样:它发出以下错误

Without -O2 g++ behaves like I would want it to behave: it issues the following error

const-init.cpp:8:19: warning: ‘i’ is used uninitialized in this function [-Wuninitialized]
     const int i = i;
                   ^

那么为什么编译器在使用<$ c $时假设i为0 c> -O2 是否由于这种假设而标记甚至删除整个循环?

So why does the compiler assume 0 for i when using the -O2 Flag and even deletes the whole loop because of this assumption?

推荐答案

其名称是未定义的行为,将 i 设置为0只是一种可能的结果。

Its name is "undefined behaviour" and setting i to 0 is just one possible outcome.

这篇关于用自身初始化C ++ const变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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