rulururu

post Constants - a vexatious issue

February 10th, 2008

Filed under: C++ — Kai @ 8:02 pm

I assume that all C++ programmers always wonder how the clearest way declaring constants might be when using them. It’s every again time a really vexatious issue…

A constant is similar to a variable in the sense of representing a memory location (or simply, a value). As you probably know, it is different from a normal variable and cannot change it’s value in the program - it must stay for ever stay constant. In general, constants are useful for preventing program bugs and logical errors.

There are two main ways of defining constants in C++, and I’ll review and compare both of them, seeing their advantages and disadvantages.

Let’s see the good old, C way first:

#define Pi 3.1415

Maybe better would be:

const float fPi = 3.1415;

First think we can notice here, is that we defined a type for the constant, float. This allows some type checking by the compiler.
Another advantage is that the scope of the constant can be definied, you can set it either private or global, while using the first method (#define), the constant can only be globally declared.

If you like to contradict to me you’d probably say that for example the suffix “L” can be added to the #define and the variable can be used as a long data type :

#define Pi 3.1415L

Although this is a better way than declaring it without a type information you’d prefer the const keyword just for the reason that it’s not old c style.

No Comments »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a comment

ruldrurd
Powered by WordPress, Content and Design by Kai Bellmann
Entries (RSS) and Comments (RSS)