Click here to Skip to main content
15,889,281 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
Hi,

as title said, can we override #define's value

like
C++
#include<stdio.h>
#define LIM 5

// in main function
// scanf x's value and assign it to LIM
// LIM = x;


can we do that ??
Posted

The answers given to your question and this link show why it is better to use a static const than a #define in this case.

http://stackoverflow.com/questions/1637332/static-const-vs-define[^]

However #define can be used to create a macro and this is quite legal though I would not recommend it.

C++
#define LIM (x)

 int x = 5;

 cout << LIM << endl;

 x = 6;

  cout << LIM << endl;
 
Share this answer
 
v2
As the other solutions have indicated, you can't change a value at runtime, but you can change the compile time definition of a macro during the compile process. For example:

C++
void foo()
{
#define LIM 5
    int zork[LIM]; // defined as size 5

#undef LIM
#define LIM 42
    int blork[LIM];  // defined as size 42

#undef LIM
#define LIM 123

    // At this point, LIM is 123, but zork is still size 5 and blork is still
    // size 42. This does not change during the compile process or during runtime.
#undef LIM
    // At this point, LIM is undefined.
}
 
Share this answer
 
Comments
[no name] 18-Sep-13 0:01am    
Yes and the #undef merely removes warnings.
H.Brydon 18-Sep-13 0:40am    
Hmmm ... warnings bad juju.
No, you cannot override a #define constant with variable at run-time. The reason is simple: #define statements are processed by the compiler -- at compile-time, i.e. long before your program runs. And the compiler inserts those values as constants in your program code.

But you can do the following:
C++
#define LIM 5

void MyFunction ()
{
    int x;

    if (!scanf ("%d", &x) != 1)
        x = LIM;
    ...    
}
 
Share this answer
 
v2
Comments
ridoy 17-Sep-13 16:39pm    
good explanation,5ed!
nv3 17-Sep-13 16:55pm    
Thank you!
You cannot do that.

The #define are replaced (textually) in by the pre-compilation phase of the compiler.
 
Share this answer
 
Comments
ridoy 17-Sep-13 16:39pm    
agree,5ed!
Sergey Alexandrovich Kryukov 17-Sep-13 18:33pm    
Of course, a 5.
—SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900