0

I'd like to end a program with error message and return value 100 from inside of function:

    void readSize(int *rows, int *cols) {
        while(!(scanf("%d %d", rows, cols))) {
            fputs("Error: Incorrect input!\n", stderr);
            return 100;
        }
    }

I want that return to return 100 like if it was from the main() if you know what I mean. I tried goto, but it can't jump between functions. Any ideas?

tomashauser
  • 561
  • 3
  • 16
  • 6
    You want `exit(100)`. – Steve Summit Oct 31 '19 at 10:57
  • @Blaze That was on purpose to show, what I'd like to do. – tomashauser Oct 31 '19 at 10:58
  • 1
    Also, you've got some problems with your `scanf` call. I think you want `if`, not `while`, and the condition should be `!= 2`, not (in effect) `== 0`. (My point is that if `scanf` returns 1, or -1, or in fact anything other than 2, that's a failure.) – Steve Summit Oct 31 '19 at 11:00
  • @SteveSummit Thanks! I'll leave it there in case someone searches for this in a similar phrasing later. :) – tomashauser Oct 31 '19 at 11:00
  • @SteveSummit Both the question and answer is simple, but I think you should write that as an answer. – klutt Oct 31 '19 at 11:04
  • @tomashauser yes, you should not correct the code that was posted (unless it wasn't the code you were using) or the question won't make any sense. – Weather Vane Oct 31 '19 at 11:14
  • Is there a way how to flag a comment as a correct answer to my problem? I can't find it anywhere. – tomashauser Oct 31 '19 at 11:19

1 Answers1

1

From Steve Summit in the comments. Just use exit(100)

The function you're looking for is exit(). As argument you pass the return code you want to return. There are standard macros for this, like EXIT_SUCCESS or EXIT_FAILURE but you can choose an int of your choice. When used in function main, exit(x) is equivalent to return x.

You can read about the exit function here: https://port70.net/~nsz/c/c11/n1570.html#7.22.4.4

Another detail is that while(!(scanf("%d %d", rows, cols))) is wrong. If both row and cols are successfully assigned, scanf will return 2. Sure, what you have written will be treated as success if it returns 2, but it will do the same if it returns 1, which should be treated as a failure. Instead, do while(!(scanf("%d %d", rows, cols)) == 2), or even better if it suits your needs, consider a combination of fgets and sscanf as described here

klutt
  • 30,332
  • 17
  • 55
  • 95