有什么方法可以保护变量以在C中运行时进行修改? [英] Is there any way of protecting a variable for being modified at runtime in C?

查看:66
本文介绍了有什么方法可以保护变量以在C中运行时进行修改?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有任何方法可以保护变量以在初始化后进行修改(例如在运行时常量化变量)。例如:

I was wondering if there is any way of protecting a variable for being modified once initialized (something like "constantize" a variable at runtime ). For example:

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    int v, op;
    scanf( "%d", &op );
    if( op == 0 )
        v = 1;
    else
        v = 2;
// here transform v to a constant...
    .
    .
// ...and that any attempt to modify v yields to an error.
    .
    .
    return EXIT_SUCCESS;
}


推荐答案

您可以得出以下结果:输入为 const 像这样:

You can make the result of the input be const like this:

int func()
{
    int op = 0;
    scanf( "%d", &op );
    if( op == 0 )
        return 1;
    else
        return 2;
}

int main()
{
    const int v = func();
    // ...
}

NB。当然,没有方法可以防止程序稍后发生的未定义行为似乎改变了 v (因为根据定义,未定义行为可以产生任何效果)。

NB. Of course, there is no way to prevent undefined behaviour happening later in the program which appears to change v (since undefined behaviour can, by definition, have any effect).

这篇关于有什么方法可以保护变量以在C中运行时进行修改?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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