LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   C++: #define OR const int ? (https://www.linuxquestions.org/questions/programming-9/c-define-or-const-int-370533/)

Hady 10-07-2005 02:07 AM

C++: #define OR const int ?
 
Hi!

If SPEED is the most important thing in a program,

which is faster

#define wordSize 256
OR
const int wordSize = 256;

char word[wordSize]; // This line is called many times



and please explain why?

Thanks in advance for your time and help.

mailelam 10-07-2005 02:10 AM

It's the same thing on every decent compiler.
The only time you may save is some nanoseconds during compile time :)

Hady 10-07-2005 02:34 AM

Thanks for your reply.

I know my question might seem trivial but
I care about Every nanosecond at RUN time.
I don't care about compile time.

Could anyone assure me that at run-time it will be the same if that 'wordSize' will be used too many times in the code?

In case it's the exactly the same speed at Run-time, which is better to use?

Thanks!

Ankit mittal 10-07-2005 02:59 AM

hello friend..

if u are concwern every nano sec of run time.

then i think #define is better way to write.
because it process by prepocessor and preprocessor put its value to all palces before any complition.
so at run time there is no need to substituting varible value.
i think my answer clarify u deference and help u.

bigearsbilly 10-07-2005 03:24 AM

if speed is so important why use C++?

I think you'll find it won't make a gnats of difference compared
with opening a file or printing a single character.

Make your code readable, simple and maintainable
that's good engineering.

dovkruger 10-07-2005 11:43 AM

good coding
 
don't use #define, it's not clean or typesafe

you can use an enum to represent integer values:

enum { myconst = 256 };

There should be no difference between the variable and the enum in performance IN SOME CASES (see below for how to optimize your code), unless you are doing things with pointers that the compiler does not understand:
const int x = 5;
int* p = (int*)&x; // you shouldn't do this anyway.

The compiler will panic and not to optimizations when you pull this kind of mischief.

If you have constant subexpressions:

double f(const double x, const double y) {
return x + y;
}

There is a world of a difference between this and:

inline double f(const double x, const double y) {
return x + y;
}

z= f(3,4)

Merely declaring them const means that they don't change in the program. inlining them shows the compiler that in fact, they are constants and can be folded.


All times are GMT -5. The time now is 05:54 PM.