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?
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