Home > Enterprise >  How to directly specify some values as an argument in C instead of specifying an array name or a p
How to directly specify some values as an argument in C instead of specifying an array name or a p

Time:11-12

Can I write a function in C to accept an array of values like this:

void someFunction(/*the parameter for array*/){
    //do something
}

someFunction({ 1, 2, 3 });

CodePudding user response:

There are various ways of doing this.

Method 1

Using initializer_list as parameter type.

void someFunction(std::initializer_list<int> init){
   
}
int main()
{
    
   someFunction({ 1, 2, 3 });
}

Method 2

Using std::vector<int> as parameter type.

void someFunction(const std::vector<int> &init){
   
}
int main()
{
    
   someFunction({ 1, 2, 3 });
}

CodePudding user response:

You could get inspiration from e.g. std::min and use std::initializer_list

void someFunction(std::initializer_list<int> ints) {
    for (int i : ints)
    {
        std::cout << i << '\n';
    }
}

CodePudding user response:

Yes you can.
One option is to use std::vector, and in your specific case std::vector<int> const& for the parameter of someFunction:

#include <iostream>
#include <vector>

void someFunction(std::vector<int> const & a) 
{
    for (int i : a)
    {
        std::cout << i << ", ";
    }
    std::cout << std::endl;
}


int main()
{
    someFunction({ 1, 2, 3 });
    return 0;
}

Output:

1, 2, 3,
  •  Tags:  
  • c
  • Related