title: What is the best way to return an error from a function when I'm already returning a value?
body: <p>I wrote a function in C that converts a string to an integer and returns the integer. When I call the function I also want it to let me know if the string is not a valid number. In the past I returned -1 when this error occurred, because I didn't need to convert strings to negative numbers. But now I want it to convert strings to negative numbers, so what is the best way to report the error?</p>
  
  <p>In case I wasn't clear about this: I don't want this function to report the error to the user, I want it to report the error to the code that called the function. ("Report" might be the wrong word to use...)</p>
  
  <p>Here's the code:</p>
  
  <pre><code>s32 intval(const char *string) {
      bool negative = false;
      u32 current_char = 0;
  
      if (string[0] == '-') {
          negative = true;
          current_char = 1;
      }
  
      s32 num = 0;
      while (string[current_char]) {
          if (string[current_char] &lt; '0' || string[current_char] &gt; '9') {
              // Return an error here.. but how?
          }
  
          num *= 10;
          num += string[current_char] - '0';
          current_char++;
      }
  
      if (negative) {
          num = -num;
      }
  
      return num;
  }
  </code></pre>