Products > 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

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:

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 ---

Ian.M:
Finally, if you can tolerate a GCC specific departure from ANSI C, you can use case ranges:

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

    // Other case blocks that require separate handling
}

--- End code ---
which tidies it up considerably.  See: https://gcc.gnu.org/onlinedocs/gcc/Case-Ranges.html

N.B. the ellipses indicating a range should always be separated by whitespace from the range limits.

golden_labels:
Sometimes the mot obvious is not obvious:
--- Code: ---if (Value >= 1 && Value <= 3) {
    OutputValue = Value + 275;
}
--- End code ---

Navigation

[0] Message Index

[#] Next page

There was an error while thanking
Thanking...
Go to full version
Powered by SMFPacks Advanced Attachments Uploader Mod