Reputation: 675
I want to replace directive
#define MAX_LINE 15
with variable value.
For example of behavior, if something ( text ) contains 15 or more lines #define MAX_LINE to return 15 else if the text contains less than 15 lines #define MAX_LINE to return numbers of lines.
for( i = 0; i < MAX_LINE; i++ ) {
/* print lines in expandable menu window */
}
is this possible?
Upvotes: 1
Views: 989
Reputation: 320431
Then replace it
int MAX_LINE = 15;
or
int max_line = 15;
#define MAX_LINE max_line
Just keep in mind that MAX_LINE
will no longer be a constant, i.e. you will not be able to use it anywhere a constant is required.
Basically, once it became a variable value, it no longer has anything to do with the preprocessor. It is just an ordinary variable now. Make it a variable, name it appropriately and forget about #define
.
Upvotes: 3
Reputation: 129011
#define
s simply replace some text with some other text. You could, for example, use this:
#define MAX_LINES ((num_lines > 15) ? 15 : num_lines)
Then you can use MAX_LINES
as before in some statements. However, it won't work in all situations. You may have had code that looked like this:
const char *lines[MAX_LINES];
With the old #define
, MAX_LINES
was 15, so it expanded to this:
const char *lines[15];
That should be valid in any standards-compliant compiler. However, say you used our new #define
. Expanded, it would look like this:
const char *lines[((num_lines > 15) ? 15 : num_lines)];
Supposing that was a global declaration, that would be invalid. Even if it was just a local declaration, it would only be valid if the compiler supports variable-length arrays.
If I were you, I'd simply try to get whatever you're trying to do to work without #define
ing MAX_LINES
to a non-constant expression; it's clearer that way and it will be more obvious where it would be invalid to use MAX_LINES
.
Upvotes: 0