1

I have a an application header file in c where I mention the variable.

#VAR_X        "testData"

User can change this variable but I want to restrict it's length to maximum of 50.If user tries to make it more than 50 there should be an error on building the code.

I have done like this in the application.h:

#define __IS_MORE            if((strlen(VAR_X) - 50) > 0) 1:0;

and in application.c at the top .

#define application.h
#if defined(__IS_MORE)
#error "Size is more than the maximum size"
#endif

But no matter what I put in the VAR I always get the #error directive "Size is more than the maximum size"

What wrong I am doing?

Raulp
  • 7,758
  • 20
  • 93
  • 155

3 Answers3

4

At compile time, you can do this by using a technique called as static assert. you can find the details here. Assuming a STATIC_ASSERT macro is defined as explained in the link, you can do the following to check if VAR_X exceeds the length (Here I assume that VAR_X is a macro as in #define VAR_X "...")

STATIC_ASSERT(sizeof(VAR_X) <= 50, "Size of VAR_X is more than the maximum size");

Some example code

#define STATIC_ASSERT(COND,MSG) typedef char static_assertion_##MSG[(COND)?1:-1]
#define VAR_X "012345678912912"

STATIC_ASSERT(sizeof(VAR_X) <= 50, Size_of_VAR_X_is_more_than_the_maximum_size);

int main()
{
    return 0;
}
Community
  • 1
  • 1
user1969104
  • 2,340
  • 14
  • 15
  • doesn't seems to be working.Or am I missing something here.Is "sizeof" also expands into some macro? – Raulp Nov 02 '15 at 07:59
  • A macro is replaced with its contents by pre-processor. Compiler sees it as sizeof("testData") and does not know about the macro expansion. I have copy pasted some example working code. – user1969104 Nov 02 '15 at 10:19
1

#define and #if are part of the C preprocessor and are evaluated before compiling the code.

The line #if defined(__IS_MORE) simply evaluates if the label __IS_MORE has been defined, which it has. Therefore the #error is processed.

What you are wanting to do (make sure that programmer can't define VAR_X with more than 50 characters) can not be done at the preprocessor level. The best you can do is put a run time check at the start of the code if you need to.

waterjuice
  • 829
  • 5
  • 14
0

#ifdef (and #if defined(..)) are precompiler checks and are true if the symbol is defined at the point the code is compiled.

It doesn't matter WHAT you define #define __IS_MORE as, the macro IS defined as something, hence the error.

As your check requires evaluation of strlen at run time, you could look instead at a construct like assert to enforce your check.

Community
  • 1
  • 1
StuartLC
  • 104,537
  • 17
  • 209
  • 285