什么是符号常量的意义呢? [英] What Is The Point of Symbolic Constants?

查看:175
本文介绍了什么是符号常量的意义呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法理解什么是在C符号常量的地步,我肯定有他们的理由,但我似乎无法明白为什么你不会只使用一个变量。

 的#include<&stdio.h中GT;主要()
{
    法尔浮动摄氏;
    浮动下限,上限,步;    低级= 0;
    上= 300;
    步骤= 20;    的printf(%S \\ t%S \\ n,飞轮海,摄氏);
    法尔=低;
    而(法尔< =上){
        摄氏=(5.0 / 9.0)*(法尔 - 32.0);
        的printf(%3.0F \\ t \\ t%3.2F \\ n,法尔,摄氏);
        法尔=法尔+步骤;
    }}

VS

 的#include<&stdio.h中GT;#定义LOWER 0
#定义UPPER 300
STEP的#define 20主要()
{
    法尔浮动摄氏;    的printf(%S \\ t%S \\ n,飞轮海,摄氏);
    法尔=更低;
    而(法尔< = UPPER){
        摄氏=(5.0 / 9.0)*(法尔 - 32.0);
        的printf(%3.0F \\ t \\ t%3.2F \\ n,法尔,摄氏);
        法尔=法尔+ STEP;
    }}


解决方案

的(pre)编译器知道符号常量不会改变。它可以代替在编译时常数的值。如果常量是一个变量,它通常无法弄清楚,该变量永远不会改变的价值。其结果是,编译code的读取分配给该变量的存储器,其可以使程序稍慢,以及较大的值。

在C ++中,你可以声明一个变量为常量,它告诉编译器pretty同样的事情。这就是为什么符号常量在C ++中皱起了眉头。

I've having trouble understanding what is the point of Symbolic Constants in C, I am sure there is a reason for them but I can't seem to see why you wouldn't just use a variable.

#include <stdio.h>

main()
{
    float fahr, celsius;
    float lower, upper, step;

    lower = 0;
    upper = 300;
    step = 20;

    printf("%s\t %s\n", "Fahrenheit", "Celsius");
    fahr = lower;   
    while (fahr <= upper) {
        celsius = (5.0 / 9.0) * (fahr - 32.0);
        printf("%3.0f\t\t %3.2f\n", fahr, celsius);
        fahr = fahr + step;
    }

}

Vs.

#include <stdio.h>

#define LOWER   0
#define UPPER   300
#define STEP    20

main()
{
    float fahr, celsius;

    printf("%s\t %s\n", "Fahrenheit", "Celsius");
    fahr = LOWER;   
    while (fahr <= UPPER) {
        celsius = (5.0 / 9.0) * (fahr - 32.0);
        printf("%3.0f\t\t %3.2f\n", fahr, celsius);
        fahr = fahr + STEP;
    }

}

解决方案

The (pre)compiler knows that symbolic constants won't change. It substitutes the value for the constant at compile time. If the "constant" is in a variable, it usually can't figure out that the variable will never change value. In consequence, the compiled code has to read the value from the memory allocated to the variable, which can make the program slightly slower and larger.

In C++, you can declare a variable to be const, which tells the compiler pretty much the same thing. This is why symbolic constants are frowned upon in C++.

这篇关于什么是符号常量的意义呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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