Hi,

Simple question but why would someone use #define.
Whats the difference between;

#define sum 1 and const int sum = 1;

both can't be changed and anywhere you sum its going to be 1!.

Many thanks

Alex

Dani AI

Generated

Brief, practical follow-up to what and started: the simple examples show two ways to give a name to a value, but they behave differently in ways that matter for safety, maintenance and modern C++ style. Macros are a text-level facility useful for include-guards and conditional compilation, but they do not respect scope or types and can expand in surprising ways. Typed constants (and the newer constexpr/inline features) give compiler checks, proper linkage, and better debugging information.

Common gotcha: function-like macros silently re-evaluate arguments and can suffer from precedence issues. For example:

#define SQR(x) ((x)*(x))
int i = 2;
int r = SQR(++i); // expands to ((++i)*(++i)) — unexpected side effects

A safer modern alternative is a constexpr/template function:

template<typename T>
constexpr T sqr(T x) { return x * x; }

Recommendations that hold up over time:

  • Prefer constexpr, enum/enum class, or inline variables (C++17) for named constants so the compiler enforces types and linkage.
  • Reserve macros for include-guards and conditional compilation or for cases where no language feature can express the intent.
  • When debugging macros, inspect preprocessor output (compiler option like g++ -E) to see exact expansions.
  • Watch for name collisions since macros ignore namespaces.

For authoritative reference on the preprocessor and modern compile-time features, see the cppreference pages for the preprocessor and constexpr:
c++ preprocessor
c++ constexpr

Recommended Answers

All 3 Replies

The first is a preprocessor directive, before the compiler compiles your code, it will go through and replace sum with 1. The second declares a variable in memory to hold that quantity. I'm sure it can be argued as to which is best, but the "const int" is probably more common in C++ (when it comes to numeric constants).

thats great, thanks

Alex

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.