简体   繁体   English

C编程:用户输入标记值后,如何终止程序?

[英]C programming: how do I terminate the program after the user enters a sentinel value?

so I first #define SENTINEL -1 所以我首先#define SENTINEL -1

and in a certain function, I set up an if statement 在某个函数中,我设置了一个if语句

void blahblah(blah)
{
   printf("Enter an integer (-1 to quit)");
   scanf("%d", &value);
   if (value == SENTINEL)
     return;
}

but for some reason it's not terminating the program like I want it to? 但是由于某种原因,它并没有像我想要的那样终止程序?

return doesn't mean quit, it just means return from the function.... in your code there, the if statement is useless, because the function will return anyways if the if statement is false. return并不意味着退出,而只是意味着从函数中返回。...在您的代码中,if语句是无用的,因为如果if语句为false,该函数将始终返回。

You probablly want to return a value from blahbalh to say to quit. 您可能想从blahbalh返回一个值,说要退出。

If you wish your entire program to terminate, please replace return with a exit(0); 如果您希望整个程序终止,请用exit(0);代替return exit(0); . Also, please ensure that the data type of value is int and not unsigned int . 另外,请确保value的数据类型为int而不是unsigned int

The normal way would be to set a flag to cause a return; 通常的方法是设置一个导致返回的标志。 in main() - but you can use exit() to immediately abort a program from any part of the code. 在main()中-但是您可以使用exit()立即从代码的任何部分中止程序。

Be aware that if you use exit() the program will just end there and you wont get any termination/clean up code you might want to run. 请注意,如果您使用exit(),程序将仅在此处结束,并且您不会获得任何可能要运行的终止/清理代码。

edit again, was thinking in the wrong language! 再次编辑,当时使用错误的语言! exit() expects an int parameter signifying the status of the return, either EXIT_SUCCESS or EXIT_FAILURE exit()需要一个int参数来表示返回状态,即EXIT_SUCCESS或EXIT_FAILURE

my bad! 我的错!

There is no reason for program to terminate, you are only leaving (return) a function when value == SENTINEL. 没有理由终止程序,仅当value == SENTINEL时才离开(返回)一个函数。

You function also has three problems; 您的职能还存在三个问题; if value != SENTINEL then you don't return a function which is undefined behaviour; 如果值!= SENTINEL,那么您不会返回未定义行为的函数; parameter blah is missing a type (int blah) ; 参数blah缺少类型(int blah); and value should be global for that function to work. 价值应该是全球性的,以使该职能发挥作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM