Consider this code;
#define A 5
#define B 3
int difference = A - B;
does value of “difference” is hardcoded as “2” in compile time, or does it get calculated on runtime?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The
AandBmacros are a bit of a distraction. This:is exactly equivalent to this:
so let’s discuss the latter.
5 - 3is a constant expression, which is an expression that “can be evaluated during translation rather than runtime, and accordingly may be used in any place that a constant may be”. It’s also an *integer constant expression”. For example, a case label must be an integer constant expression, so you could write either this:or this:
But note that the definition says that it can be evaluated during translation, not that it must be. There are some contexts that require constant expressions, and in those contexts the expression must be evaluated at compile time.
But assuming that
differenceis declared inside some function, the initializer is not one of those contexts.Any compiler worth what you pay for it (even if it’s free) will reduce
5 - 3to2at compile time, and generate code that stores the value2indifference. But it’s not required to do so. The C standard specifies the behavior of programs; it doesn’t specify how that behavior must be implemented. But it’s safe to assume that whatever compiler you’re using will replace5 - 3by2.Even if you write:
a compiler could legally generate code that loads the value
5into a register, subtracts3from it, and stores the contents of the register intodifference. That would be a silly thing to do, but the language standard doesn’t exclude it.As long as the final result is that
differencehas the value2, the language standard doesn’t care how it’s done.On the other hand, if you write:
then the compiler must compute the result so it can diagnose the error (you can’t have two case labels with the same value.
Finally, if you define
differenceat file scope (outside any function), then the initial value does have to be constant. But the real distinction in that case is not whether5 - 3will be evaluated at compile time, it’s whether you’re allowed to use a non-constant expression.Reference: The latest draft of the 2011 C standard is N1570 (large PDF); constant expressions are discussed in section 6.6.