Click here to Skip to main content
15,895,142 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hello All,

I want to write the switch case statement such that ,

for each case i will be checking condition. e.g.

switch(expr)

case (if statement to be written here):

how to achieve this functionality.

What I have tried:

switch(expr)
case if(i%3==0 && i%5==0) // throwing compile time error.
Posted

Chances are, you do not need a switch statement there, but a if () { } else if () { } else () { } statement instead.

Here, expr and i do not seem to be directly related to each other, so a switch statement is not an option.
 
Share this answer
 
Try something like:
C++
if (condition 1)
    {}
else if (condition 2)
    {}
else
    {}


Advice! Take time to learn properly the language.
Here is links to references books on C and C++ by the authors of the languages. Note than C is the ancestor of C++, so knowing C is always useful with C++.
The C Programming Language - Wikipedia, the free encyclopedia[^]
https://hassanolity.files.wordpress.com/2013/11/the_c_programming_language_2.pdf[^]
http://www.ime.usp.br/~pf/Kernighan-Ritchie/C-Programming-Ebook.pdf[^]

C++ Programing Language[^]

[UpDate]
Quote:
i already know the thing you provided but i want to write the case statement as below
or moreover in place of case 1 i want case if(conditional expression)
It does not exist in the language !

[UpDate]
Quote:
I want to optimize the below code using switch case statement.

i have already written this code.
C++
if (i % 3 == 0 && i % 5 == 0)
                {
                    Console.WriteLine("Both True");
                }
                if (i % 3 == 0)
                {
                    Console.WriteLine("Three True");
                }
                if (i % 5 == 0)
                {
                    Console.WriteLine("Five True");
                }
You can't ! it is already optimized !
 
Share this answer
 
v4
Well that's meaningless (see switch (C# Reference)[^])

You could write
C#
switch (expr)
{
case 0:
  if(i%3==0 && i%5==0)
  {
    //...
  }
  break;
case 1:
  //...  
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900