📜  C++中的运行时和编译时常量

📅  最后修改于: 2021-05-30 02:06:13             🧑  作者: Mango

运行时常数

这些是常数,其各自的值只能在运行源代码时获知或计算。运行时常量比编译时常量慢一点,但比编译时常量灵活。但是,一旦初始化,就不能更改这些常量的值。

下面是用于说明运行时常量的程序:

C++
// C++ program to illustrate
// Run-time Constants
#include 
using namespace std;
  
// Driver Code
int main()
{
    // Input a variable
    double electonmass;
    cin >> electonmass;
  
    // Define a constant
    // and initialize it at
    // run-time
    const double electon_mass{ electonmass };
  
    // Known to the compiler
    // at the run-time
    cout << electon_mass << endl;
  
    return 0;
}


C++
// C++ program to illustrate
// compile-time constants
#include 
using namespace std;
  
// Driver Code
int main()
{
    // Declare and initialize
    // compile time constant
    const double electron_q{ 1.6e-19 };
  
    // Value known to compiler
    // at compile-time
    cout << electron_q << endl;
  
    return 0;
}


输出:
2.07335e-317

编译时常数

这些是常数,其各自的值在编译源代码时是已知的或已计算出的值。编译时常量比运行时常量快,但不如运行时常量灵活。

下面是用于说明编译时常数的程序:

C++

// C++ program to illustrate
// compile-time constants
#include 
using namespace std;
  
// Driver Code
int main()
{
    // Declare and initialize
    // compile time constant
    const double electron_q{ 1.6e-19 };
  
    // Value known to compiler
    // at compile-time
    cout << electron_q << endl;
  
    return 0;
}
输出:
1.6e-19

运行时和编译时常量之间的差异

                            Compile-time constants                                      Run-time constants                  
1. A compile-time constant is a value that is computed at the compilation-time.  Whereas, A runtime constant is a value that is computed only at the time when the program is running.
2. A compile-time constant will have the same value each time when the source code is run.

A runtime constant can have a different value each time the source code is run.

3

It is generally used while declaring an array size.

It is not preferred for declaring an array size.

4 If you use const int size = 5 for defining a case expression it would run smoothly and won’t produce any compile-time error. Here, if you use run-time constant in your source code for defining case expression then it will yield a compile-time error.
5 It does not produces any compile time error when used for initializing an enumerator.

Same compilation error, if runtime constant is used for initializing an enumerator.

要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”