crefactoringexiterrnostrerror

How to export error-handling to a function in C using <errno.h>


I am checking if user enters the correct number and type of cmd arguments when calling main.

I thought it would be a great idea to write a function, which prints out some text, so I can reuse it when checking for NULL pointers. I included <errno.h>.

void errcall()
{
  perror("Error printed by perror()");
  exit(EXIT_FAILURE);
}

Then I wrote a function to check if arguments are right and sufficient.

void err_cmd_handle(int argc_input)
{
  if(argc_input==1 || argc_input>2)
    errcall(); 
}

When I call this in main, giving int argc as an argument to err_cmd_handle(), then I get a success, even when I did not give any arguments besides starting the program. Why does the condition fail to check correctly?

int main(int argc,char* argv[])
{
  err_cmd_handle(argc);
  return 0;
}

Solution

  • If you take your complete code with required headers:

    #include <stdio.h>
    #include <errno.h>
    #include <stdlib.h>
    
    void errcall()
    {
      perror("Error printed by perror()");
      exit(EXIT_FAILURE);
    }
    void err_cmd_handle(int argc_input)
    {
      if(argc_input==1 || argc_input>2)errcall(); 
    }
    
    int main(int argc,char* argv[])
    {
        err_cmd_handle(argc);
        return 0;
    }
    

    and then run it with no arguments, the output is:

    Error printed by perror(): Success 
    

    Clearly the validation has worked because errcall() has been called. The text "Success" is simply because the value of errno is zero - because nothing has set it.

    Your original code before you changed the question had:

    if(argc_input==1 || argc_input>2)errcall();
      else exit(EXIT_SUCCESS); 
    

    So when you stated:

    then I get a success, even when I did not give any arguments besides starting the program

    It was reasonable to assume that it was terminating via exit(EXIT_SUCCESS); - that is clearly not the case. It was also you I originally assumed that errno had nothing to do with the question because it seemed that errcall() cannot have been called if it returned EXIT_SUCCESS. Hopefully you see why your question caused so much confusion and comment?