Why is volatile needed in C?

前端 未结 18 2232
攒了一身酷
攒了一身酷 2020-11-22 04:07

Why is volatile needed in C? What is it used for? What will it do?

18条回答
  •  鱼传尺愫
    2020-11-22 04:49

    A marginal use for volatile is the following. Say you want to compute the numerical derivative of a function f :

    double der_f(double x)
    {
        static const double h = 1e-3;
        return (f(x + h) - f(x)) / h;
    }
    

    The problem is that x+h-x is generally not equal to h due to roundoff errors. Think about it : when you substract very close numbers, you lose a lot of significant digits which can ruin the computation of the derivative (think 1.00001 - 1). A possible workaround could be

    double der_f2(double x)
    {
        static const double h = 1e-3;
        double hh = x + h - x;
        return (f(x + hh) - f(x)) / hh;
    }
    

    but depending on your platform and compiler switches, the second line of that function may be wiped out by a aggressively optimizing compiler. So you write instead

        volatile double hh = x + h;
        hh -= x;
    

    to force the compiler to read the memory location containing hh, forfeiting an eventual optimization opportunity.

提交回复
热议问题