1

so I first #define SENTINEL -1

and in a certain function, I set up an if statement

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?

iopeia
  • 11
  • 1
  • 2
  • `int x = scanf("%d %d", &foo, &bar);` Assuming I enter "1234 hello", what will x be? Furthermore, which character constant would you expect getchar() to return? `int y = scanf("%d %d", &foo, &bar);` Assuming scanf encounters EOF or some other error here, what will y be? `int z = scanf("%d %d", &foo, &bar);` Assuming scanf successfully reads and assigns a value into the two int variables foo and bar, what will z be? – autistic Feb 12 '13 at 02:25

4 Answers4

1

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.

You probablly want to return a value from blahbalh to say to quit.

Keith Nicholas
  • 43,549
  • 15
  • 93
  • 156
0

If you wish your entire program to terminate, please replace return with a exit(0);. Also, please ensure that the data type of value is int and not unsigned int.

Ganesh
  • 5,880
  • 2
  • 36
  • 54
0

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.

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.

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

my bad!

David Burford
  • 791
  • 2
  • 8
  • 17
  • using exit(); gives me warnings: implicit declaration of function 'exit'; incmopatible implicit declaration of built-in function 'exit; too few argumetns to function exit – iopeia Feb 11 '13 at 23:50
  • see my edit to see what value you should pass to exit. you can also look it up at: http://www.acm.uiuc.edu/webmonkeys/book/c_guide/2.13.html#exit – David Burford Feb 11 '13 at 23:53
0

There is no reason for program to terminate, you are only leaving (return) a function when value == SENTINEL.

You function also has three problems; if value != SENTINEL then you don't return a function which is undefined behaviour; parameter blah is missing a type (int blah) ; and value should be global for that function to work.

  • Where did you get the impression that blahblah expects a function to be returned? I see no problem there. The problem I see is that the return value of scanf isn't checked, and so there is no guarantee that value will contain a useful value. – autistic Feb 12 '13 at 02:20