Computing > Programming

C Programming - Refer to switch structure value inside each case statement

(1/3) > >>

Sergio:
Hello,
I will try to do my best explaining my question.
In a case structure like this one:

--- Code: ---switch(Value){
    case 1:   
        OutputValue= "CaseValue" + 275;
        break;               
    case 2:     
        OutputValue= "CaseValue" + 275;
        break;             
    case 3:   
        OutputValue= "CaseValue" + 275;
        break;             
}

--- End code ---

Would it be possible to refer to each case value inside the case statement without writing manually the value?
On the example, the three possible results would be 276, 277 and 278.
The example is very simple, but I have code where I use several times the "CaseValue" inside the statement and I repeat the structure for several Case values. So using a reference to the value would allow to copy-paste the structure without having to modify each value manually and maybe avoiding human mistakes

Thank you in advance for any help

evb149:
I'm not sure what you mean.

In each case statement the switch argument (Value) is the 'CaseValue' by definition.

switch(Value){
    case 1:   
        OutputValue= Value + 275; // Value=1
        break;               
    case 2:     
        OutputValue= Value + 275; // Value=2...
        break;             
    case 3:   
        OutputValue= Value + 275;
        break;             
}

Sergio:
Never mind.
I realized how stupid the question is after posting it. Just use

--- Code: ---switch(Value){
    case 1:   
        OutputValue= Value + 275;
        break;               
    case 2:     
        OutputValue= Value + 275;
        break;             
    case 3:   
        OutputValue= Value + 275;
        break;             
}

--- End code ---

 :palm:

evb149:

const uint32_t  offset_value = Value + 275U;

switch(Value){
    case 1:   
        OutputValue= offset_value;
        break;               
    case 2:     
        OutputValue= offset_value;
        break;             
    case 3:   
        OutputValue= offset_value;
        break;             
}

Ian.M:
Oh for %DEITY%'s sake, if the case blocks in question are actually identical use fallthrough rather than copy/pasta code!

--- Code: ---switch(Value){
    case 1:   
    case 2:     
    case 3:   
        OutputValue= Value + 275;
        break;             

    // Other case blocks that require separate handling
}

--- End code ---

Navigation

[0] Message Index

[#] Next page

There was an error while thanking
Thanking...
Go to full version