簡體   English   中英

C 中 switch-case 語句的替代方法是什么?

[英]What are the alternatives to switch-case statements in C?

這是我的代碼如下:

while ( ( c = getopt( argc, argv, "s:E:b:t:vh" ) ) != -1 )
{
  switch ( c )
  {
     case 's':
        params.s = atoi( optarg );
        break;
     case 'E':
        params.E = atoi( optarg );
        break;
     case 'b':
        params.b = atoi( optarg );
        break;
     case 't':
        trace_file = optarg;
        break;
     case 'v':
        verbosity = 1;
        break;
  }
}

但是要回答這個問題,您可以使用一堆 if/else 語句:

while ( ( c = getopt( argc, argv, "s:E:b:t:vh" ) ) != -1 )
{
    if ( c == 's' )
    {
        params.s = atoi( optarg );
    }
    else if ( c == 'E' )
    {
        params.E = atoi( optarg );
    }
    else if ( c == 'b' )
    {
        params.b = atoi( optarg );
    }
    else if ( c == 't' )
    {
        trace_file = optarg;
    }
    else if ( c == 'v' )
    {
        verbosity = 1;
    }
    else
    {
        // always have some kind of default clause
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM