Error code: Difference between revisions

Content deleted Content added
STBotD (talk | contribs)
m robot Adding: es:Código de error
Emperorbma (talk | contribs)
convert to source tag
Line 4:
In programming languages without [[structured exception handling]] (e.g. in the [[C (programming language)|C programming language]]), ''error codes'' are often stored in [[global variable]]s with names like <code>errno</code>. Error codes are typically identified by number, each indicating a specific error condition. In an application that uses error codes, each function typically defines one ''return code'' to indicate a general failure. Upon receipt of that general failure return code, the programmer can check the value stored in the global error code to determine the condition that caused the function to fail. For example, to indicate that an attempt to open a file failed, a function may set the global error code to indicate the cause of the failure and return an invalid file handle. The following sample shows how the error code can be used to explain the cause of the error:
 
<source lang="c">
/* attempt to open file for reading */
FILE *fp = fopen("filename", "r");
/* if file cannot be opened, print error number and error string */
if(fp == NULL)
printf("Cannot open file, error %i, %s\n", errno, strerror(errno));
</source>
 
Since error codes are typically global variables, they can be read or written from any portion of the program. As with other global variables, that ease of access can be a source of problems in a [[thread (computer science)|multithreaded]] environment, since the process global variables could be set by more than one thread, causing a [[race condition]]. To fix this problem, [[POSIX]] defines <code>errno</code> to be a [[thread-local]] variable.
Line 29 ⟶ 31:
It was common in traditional C to declare errno manually (i.e., extern int errno) instead of including <errno.h>. It will not work with modern versions of the C library. However, on (very) old Unix systems, there may be no <errno.h> and the declaration is needed.
 
In such situations, the source code must be modified to replace all <code>extern int errno</code> lines with a single include <codesource lang="c">#include <errno.h></codesource>.
 
==See also==