1

我正在处理开关盒的问题。程序说明:main(argc,argv)。

  • argv 导致 switch 语句中的情况。根据输入,将输入相应的案例并执行相应的功能。-> 输出始终是一个结构,具有不同的内容。允许多个输入(即 main.c case1 case3)-> 两种情况都执行。
  • 我的问题是处理这些数据的传递并将其保存在全局变量中,以便打印集合。在案例内部,我将本地结果传递给全局变量,但在案例的 break 语句之后,全局再次以 NULL 开头,并且不包含已执行案例的信息。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "m.h"
output* print;

int main(int argc, char* argv[])
{

output_g* global; // global_struct
if(argc > 1)
{
    global= create_global(argc-1); // allocation for global struct

    for(int j = 0; j < argc; j++)
    {    
        switch (atoi(argv[i]))
        {
        case 123:
        {
            
            output* print= 123();
           if(print== NULL)
            {
             
                return 0;
            }
            global = fill_global(global ,print); // hands over the current struct to the global struct
        
            delete(print); // free function 
                 

        }
            break;
        
        case 456:
        {

            output* print= 456();
            if(print== NULL)
            {
        
                return 0;
            }
            global = fill_global(global ,print); // hands over the current struct to the global struct
        
            delete(print); // free function 
            
        }
            break;

        case 789:
        {
            lfnr++;
            output_1* print_liste = 789();
            if(print== NULL)
            {
        
                return 0;
            }
            global = fill_global(global ,print); // hands over the current struct to the global struct
        
            delete(print); // free function
            
        }
            break;
        
        default:
            break;
        }

        print_global_struct(file,globale_liste);
        delete_global(globale_liste);
        
    }//End for-Schleife
}// End If

return 0;
}
4

1 回答 1

0

a) 如果我理解正确,那么您不理解 switch 语句 :) switch 语句类似于嵌套的 if 语句。所以..

诠释 x = 10; switch (x) case 1: //不发生,x is not 1 case 10: //happens ... 毕竟 x 仍然是 10,除非你在 case 语句中明确地改变了它。这些案例只是检查 IF x 是一个值,它没有设置一个值。对于代码中的任何其他变量也是如此,上面的代码也不会修改 y ,除非您在不会更改的情况下明确分配它。

b) 最好不要在 case 语句中声明本地变量。他们会变得非常不稳定。标准 c++ 规则起作用:在 {} 对中声明的变量的范围限定在该 {} 对内,因此正确使用它们将为每种情况正确提供正确的范围。因此,如果您使用大括号,它将按预期工作。你不应该在一种情况下声明一个本地并在另一种情况下使用它,即使你可以让它工作(你可以)它很容易出错,因为稍后编辑代码可能会破坏事情,代码可能会让人难以阅读和使用,它通常只是一个坏主意。

一个例子:

int main()
{
int x = 3;
switch(x)
{
    
  case 1: int y;
  case 2: y = 3;
  case 3: y = 5;  
  cout << y << endl;
};
}

为我编译并运行,打印 5。它工作得很好——我没想到,使用 g++ c17 选项。就阅读和遵循意图而言,我仍然认为这是一件坏事。如果你把 {} 放在 int y 语句周围,它就不再编译了。如果您在案例 1 和案例 2 之后放置中断,它将不再编译。因此,至少要做到这一点,被编辑是“脆弱的”。

c) 运行时不会丢失任何东西。我有连续运行几个月的程序。在案件中对此也没有影响。丢失变量的风险是所有程序都面临的“ram”风险……如果长时间运行的程序因停电或故障等原因被终止,您将丢失任何未保存到文件中的内容并且必须重新开始。长时间运行的程序应该定期保存它们的状态以防止这种情况。

于 2021-02-18T13:15:03.353 回答