是写同样的几行代码好,还是调用同样的函数好?

问题描述 投票:0回答:1

写同样的代码行确实不是好的编程方法,这种方法会更好,但这是否会带来任何形式的问题,创建的变量是否仍然存在,所以我是否在浪费内存?

实际上会发生什么,当我调用foo()?

#include <stdio.h>

int foo(){
    printf("\nSelect operation. 1 to add, 2 to remove, 3 to exit.");
    printf("\n> ");
    unsigned int choice;
    scanf("%d",&choice);
    while (choice!=3){
        if (choice==1){
            // stuff
        } else if (choice==2){
            // stuff
        } else {
            printf("\nError, try again..\n");
            foo();          // what happens? does this bring to problems of any kind? will the variables created still exist, so am I wasting memory?
        }
    }
    printf("\nEnd of run.\n");
}

#include <stdio.h>

int foo(){
    printf("\nSelect operation. 1 to add, 2 to remove, 3 to exit.");
    printf("\n> ");
    unsigned int choice;
    scanf("%d",&choice);
    while (choice!=3){
        if (choice==1){
            // stuff
        } else if (choice==2){
            // stuff
        } else {
            printf("\nError, try again..\n");
            printf("\nSelect operation. 1 to add, 2 to remove, 3 to exit.");
            printf("\n> ");
            scanf("%d",&choice);
        }
    }
    printf("\nEnd of run.\n");
}

最好的方法是什么?我也读到过,比如调用main()不是好的编程方法。

c function recursion main
1个回答
1
投票

我假设循环应该是运行到用户输入'3'为止。那么主要的问题似乎是,你希望在开始时打印一次使用情况,但对每个无效的输入再打印一次。有一种方法可以做到这一点,而不需要改变太多的代码,就像这样。

#include <stdio.h>

void print_usage(void){
    printf("\nSelect operation. 1 to add, 2 to remove, 3 to exit.");
    printf("\n> ");
}

int foo(){
    print_usage();
    unsigned int choice;

    do {
        scanf("%d",&choice);

        if (choice==1){
            // stuff
        } else if (choice==2){
            // stuff
        } else if(choice!=3){
            printf("\nError, try again..\n");
            print_usage();
        }
    } while (choice!=3);

    printf("\nEnd of run.\n");
}

就像这样: scanf() 将在每次迭代中执行(所以用户可以随意输入'1'或'2'),而重复代码的问题则通过将该部分放入一个单独的小函数中来解决。

请注意,这段代码实际上和你的任何一个版本的行为都不一样。它的工作方式就像我猜想的那样,你可能希望它工作。


0
投票

如果你对 foo() 是最后一条语句(在你的例子中不是,因为还有一个对 printf但我想这只是为了调试)这被称为 "尾部调用",你的编译器可能会对其进行优化。有了这个优化,你就不会浪费堆栈,因为调用实际上被跳转所取代。

就我个人而言,我对依赖编译器的优化比较谨慎,所以你在这里使用循环可能会更好。YMMV。

编辑:我无意中发现,其实调用本身就在一个循环中,我猜你的意思是用调用代替循环。但可能我一开始就弄错了你的想法。

© www.soinside.com 2019 - 2024. All rights reserved.