0

Can on do this:

#define VARIABLE_LENGTH_CHAR_ARRAY(name, size) \
                            int temp_array_size_macro_index = size; \
                            char "#name"[temp_array_size_macro_index];

and in the main use it like:

main(){
    VARIABLE_LENGTH_CHAR_ARRAY(local_char_array, 16);    
}

would this go against the coding styles or would it be plagued with macro issues?

I know you need to be careful with the variable name!

6
  • #name[temp_array_size_macro_index]; - This is going to be the string literal "name[temp_array_size_macro_index];". I don't think you meant that. Commented Jan 27, 2019 at 15:08
  • 4
    Great way of making program error prone and impossible to read Commented Jan 27, 2019 at 15:17
  • 1
    It does not make the variables variable length Commented Jan 27, 2019 at 15:19
  • 1
    There doesn't appear to be any point in hiding the declaration of the array behind a macro. char local_char_array[16]; is a lot more understandable than VARIABLE_LENGTH_CHAR_ARRAY(local_char_array, 16); Commented Jan 27, 2019 at 16:25
  • 1
    Perhaps "A Study in Obfuscation"? Commented Jan 27, 2019 at 16:27

1 Answer 1

1

if I am right you want something like that :

#define VARIABLE_LENGTH_CHAR_ARRAY(name, size) \
                        const int size_of_##name = size; \
                        char name[size_of_##name]

int main()
{
   VARIABLE_LENGTH_CHAR_ARRAY(local_char_array, 16);
}

The name of the (now const) variable for the size now depends on the name of the array itself, that minimize the probability to have homonyms

The expansion of that code produced by gcc -E gives :

int main()
{
   const int size_of_local_char_array = 16; char local_char_array[size_of_local_char_array];
}

But to do that it is strange :

  • as __J__ I think this not helps to make the program readable
  • else where in your source size_of_local_char_array can be used but if you/someone search for its definition it will not be found
  • the macro produces two statements, and of course in that case it is not possible to group them in a block {}, this is dangerous because this is not intuitive. As you can see in your code you added a useless ';' after the use of the macro while a final ';' is already present in the macro definition
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.