hello I am tryin to complete such a task below:
int myarray[5];
switch(var)
case 1:
myarray = {1, 2, 3, 4, 5};
case 2"
myarray = {5, 4, 3, 2, 1};
...
is this possible? or do i have to creat a function for it?
hello I am tryin to complete such a task below:
int myarray[5];
switch(var)
case 1:
myarray = {1, 2, 3, 4, 5};
case 2"
myarray = {5, 4, 3, 2, 1};
...
is this possible? or do i have to creat a function for it?
The other guys know this better, but I have that idea working OK in some of my projects ( but you will need to tidy up the syntax I think )
is this possible?
No you can't declare variables inside a switch statement.
but i can change values in a switch command right?
so without using a function do can i change all the values in an array on one line?
but i can change values in a switch command right?
Yes, but you can't create a variable.
can i change all the values in an array on one line?
If you mean one statement then no.
shenhuang:
is this possible? or do i have to creat a function for it?
If you have a number of fixed arrays and just want to switch between them, you could do that by using a pointer or reference variable to access them, and just update that to point to a different array.
If you want to actually modify the content of an array, you would need to use a separate assignment for each element. This would be the only option if the content of your array is not fixed at compile time.
So like this?
Maybe set up a for_next loop if the data was amenable to that
switch(var){
case 1:
myarray[1] = 1;
myarray[2] = 2;
myarray[3] = 3;
myarray[4] = 4;
myarray[5] = 5;
break;
case 2"
myarray[1] = 5;
myarray[2] = 4;
myarray[3] = 3;
myarray[4] = 2;
myarray[5] = 1;
break;
:
:
}
It would be conventional to start the array index at zero.
Yes, unless myarray[0] was already being used for something else.
Is that the case here?
Does it matter? Its just an example.
or predefine some array's and use a pointer.
int def = {0,0,0,0,0};
int ar1 = {1, 2, 3, 4, 5};
int ar2 = {5, 4, 3, 2, 1};
int * myarray;
switch(var)
{
case 1:
myarray = ar1;
break;
case 2:
myarray = ar2;
break;
default:
myarray = def;
}
or maybe use a 2D array? is an array of arrays
int myarray[2][5] = {
{1, 2, 3, 4, 5},
{5, 4, 3, 2, 1}
};
var = myarray[i][j];