Home > Back-end >  Writing array directly to parameter gives error in c
Writing array directly to parameter gives error in c

Time:01-28

#include <iostream>

using namespace std;

template <typename VAR, unsigned int N>
int size(VAR (&arr)[N])
{
return sizeof(arr) / sizeof(arr[0]);
}

int main()
{
cout << size("Test"); //This is working

int x[] = {7, 5, 43, 8};
cout << endl
     << size(x); //And this works too

cout << endl
     << size({7, 9, 7, 9}); //When i try this its give me "no matching function for call to 'size'" error

return 0;
}

Parameter takes strings and arrays that modified outside the parameter. but i need to write the array directly inside the function like the code above. size({some integers});

CodePudding user response:

Declare the function parameter like

int size( const VAR (&arr)[N])

That is you may not bind a temporary object with a non-constant lvalue reference.

CodePudding user response:

{1,2,3,4} is not an array, but an list initialization.

Anyhow, dont reinvent the wheel. We already have std::size

#include <iostream>

int main()
{
    std::cout << std::size("Test") << '\n'; //This is working

    int x[] = {7, 5, 43, 8};
    std::cout << std::size(x) << '\n'; //And this works too

    std::cout << std::size({7, 9, 7, 9}) << '\n'; // this too

    return 0;
}

CodePudding user response:

Error is because you parameter take address of array(that is rvalue) and you give whole array(that is lvalue ) that's why code give error .

For solve this you make parameter const

`

 #include <iostream>


using namespace std;


 template <typename VAR, unsigned int N>


int size(const VAR (&arr)[N])
   {
 return sizeof(arr) / sizeof(arr[0]);
}

int main()
  {
cout << size("Test"); //This is working

 int x[] = {7, 5, 43, 8};
 cout << endl
 << size(x); //And this works too

 cout << endl
 << size({7, 9, 7, 9}); //When i try this its give me "no matching function for 
 call to 'size'" error

  return 0;
   }`

I hope you get Your answer .

  •  Tags:  
  • Related