You can do that by using std::array<std::string, 5> instead of the raw array.
For example
#include <iostream>
#include <string>
#include <array>
int main()
{
std::array<std::string, 5> mstring;
mstring = { "veena", "guitar", "sitar", "sarod", "mandolin" };
for ( const auto &s : mstring )
{
std::cout << s << ' ';
}
std::cout << '\n';
}
The program output is
veena guitar sitar sarod mandolin
Another approach when a raw array is used is to use std::initializer_list in range-based for loop. For example
#include <iostream>
#include <string>
int main()
{
std::string mstring[5];
size_t i = 0;
for ( auto s : { "veena", "guitar", "sitar", "sarod", "mandolin" } )
{
mstring[i++] = s;
}
for ( const auto &s : mstring )
{
std::cout << s << ' ';
}
std::cout << '\n';
}
The program output is the same as shown above
veena guitar sitar sarod mandolin
If your compiler supports C++ 20 then instead of these statements
size_t i = 0;
for ( auto s : { "veena", "guitar", "sitar", "sarod", "mandolin" } )
{
mstring[i++] = s;
}
you can use just one range-based for loop
for ( size_t i = 0; auto s : { "veena", "guitar", "sitar", "sarod", "mandolin" } )
{
mstring[i++] = s;
}
Cis that you can declare variables at the point of usage, and not at the top of a{ }block.std:arrayin C++, which has different capabilities) cannot be assigned in a single statement (except by techniques to do multiple assignment in one statement, for example separated by comma operator, but that's apparently not what is sought here). There's still the valid question of WHY you want to do that, since it is completely unnecessary - by DESIGN - in C++ to define any variable (or array) before it can be initialised.{ ...some code...; std::string mystring[] = {"a","b","c","d","e"}; ...code using mystring...}-- Code organized this way makes your question moot. Also recommended C++ coding style is to declare variables close to where they will be used.