-1

I have a function and I want to print the name/identifier of the array I pass as an argument.

void printArrayElements(int num[], int size){
 cout << "Array name: " << num << endl;
for(int i=0;i<size;i++){
    cout << "Array elements: " << num[i] << endl;
}
cout << endl;
}

When I pass (test,5) and (cool,10) as an argument,

int main(){

int test[5] = {1,2,3,4,5};
int cool[10] = {4,1,2,4,5,3,7,4,2,7};
printArrayElements(test,5);
printArrayElements(cool,10);

}

The result I get is,

Terminal Image: https://i.stack.imgur.com/2jEtc.png

I want the name of the array cool and jess to be printed after "Array name:" not 0x61ff0c and 0x61fee4.

cout << "Array name: " << num << endl;

By this, I intend to print the identifier of the array passed into the function as an argument. Its not working. How do I make that happen?

velox
  • 1
  • 1

2 Answers2

2

You can wrap the function in a macro, and use the preprocessor to get the variable name as a string.

#include <iostream>
#include <string>

#define printArray(x, y) printArrayElements((#x), x, y)

void printArrayElements(std::string name, int num[], int size){
    std::cout << "Array name: " << name << std::endl;
    for(int i=0;i<size;i++){
        std::cout << "Array elements: " << num[i] << std::endl;
    }
    std::cout << std::endl;
}

int main() {
    int test[5] = {1,2,3,4,5};
    int cool[10] = {4,1,2,4,5,3,7,4,2,7};

    printArray(test, 5);
    printArray(cool, 10);
}
Johann Schwarze
  • 161
  • 1
  • 4
  • 1
    Btw, to make this code build and run without error, also requires: `#include ` `#include ` in the very beginning. – ChrisZZ Apr 15 '22 at 11:29
  • Macros are evil... ...but still allow little nice tricks like [this on coliru](http://coliru.stacked-crooked.com/a/1a9d5e9a14281daf). ;-) – Scheff's Cat Apr 15 '22 at 11:50
  • One part of the evilness is that this has now redefined all `printArray` functions of all classes in every namespace. To save some typing? – BoP Apr 15 '22 at 13:29
0

This is not possible with vanilla C++ at the moment, but you can use the preprocesser to do it:

#define PRINTNAME(name) (std::cout << "name" << ":" << (#name) << std::endl)