It is always better for contants such as PI to #define them or declare them const so the compiler can optimize and it becomes less error prone. I was wondering however, how are literal numbers in statements treated? Ex:
float x;
const int y = 60;
x = y / 3.0f;
In this example how would 3.0f be treated? Would it inherit the optimizations of a constant?
What optimizations will take place depends on the compiler. In your case, both C and C++ compilers will normally have enough information to optimize your source code into identical machine code. In other words, it doesn’t really depend much on what is literal and what is constant in this code.
Having said that, the meaning of the terms literal and constant are significantly different in C and C++ (and you tagged your question C and C++ at the same time).
60and3.0fare constants, butyis not a constant. You can callya const-qualified variable if you wish, but it is not a constant in C terminology, in a sense that a singleyis not a constant expression in C.As for literals, in C language the term literal only applies to string literals (and also compound literals in C99), i.e. there are no literals in your code at all.
60and3.0.fare literals, which form constant expressions (integral and floating -point respectively).yis also a constant ofinttype, in a sense that a singleyis a constant expression in C++.The situation when you might notice the difference has nothing to do with optimizations, but rather with the way the languages are defined. For example, using the above
yin a file-scope array type declaration is legal in C++, but not in C