Movatterモバイル変換


[0]ホーム

URL:


Jump to content
WikibooksThe Free Textbook Project
Search

C++ Programming/Code/Standard C Library/Other

From Wikibooks, open books for an open world
<C++ Programming |Code/Standard C Library

Other Standard C functions

[edit |edit source]

This section will cover several functions that are outside of the previous niches but are nevertheless part of the C Standard Library.

abort

[edit |edit source]
Syntax
#include<cstdlib>voidabort(void);

The function abort() terminates the current program. Depending on the implementation, the return from the function can indicate a canceled (e.g. you used the signal() function to catchSIGABRT) or failed abort.

SIGABRT is sent by the process to itself when it calls the abort libc function, defined in cstdlib. TheSIGABRT signal can be caught, but it cannot be blocked; if the signal handler returns then all open streams are closed and flushed and the program terminates (dumping core if appropriate). This means that the abort call never returns. Because of this characteristic, it is often used to signal fatal conditions in support libraries, situations where the current operation cannot be completed but the main program can perform cleanup before exiting. It is also used if an assertion fails.

Related topics
assert -atexit -exit

assert

[edit |edit source]
Syntax
#include<cassert>assert(exp);

The assert() macro is used to test for errors. If exp evaluates to zero, assert() writes information to stderr and exits the program. If the macro NDEBUG is defined, the assert() macros will be ignored.

Related topics
abort

atexit

[edit |edit source]
Syntax
#include<cstdlib>intatexit(void(*func)(void));

The function atexit() causes the function pointed to by func to be called when the program terminates. You can make multiple calls to atexit() (at least 32, depending on your compiler) and those functions will be called in reverse order of their establishment. The return value of atexit() is zero upon success, and non-zero on failure.

Related topics
abort -exit

bsearch

[edit |edit source]
Syntax
#include<cstdlib>void*bsearch(constvoid*key,constvoid*base,size_tnum,size_tsize,int(*compare)(constvoid*,constvoid*));

The function bsearch() performs a search within a sorted array, returning a pointer to the element in question orNULL.

*key refers to an object that matches an item searched within*base. This array containsnum elements, each of sizesize.

Thecompare function accepts two pointers to the object within the array - which need to first be cast to the object type being examined. The function returns -1 if the first parameter should be before the second, 1 if the first parameter is after, or 0 if the object matches.

Related topics
qsort

exit

[edit |edit source]
Syntax
#include<cstdlib>voidexit(intexit_code);

The exit() function stops the program. exit_code is passed on to be the return value of the program, where usually zero indicates success and non-zero indicates an error.

Related topics
abort -atexit -system

getenv

[edit |edit source]
Syntax
#include<cstdlib>char*getenv(constchar*name);

The function getenv() returns environmental information associated with name, and is very implementation dependent.NULL is returned if no information about name is available.

Related topics
system

longjmp

[edit |edit source]
Syntax
#include<csetjmp>voidlongjmp(jmp_bufenv,intval);

The function longjmp() behaves as a cross-functiongoto statement: it moves the point of execution to the record found in env, and causes setjmp() to returnval. Using longjmp() may have some side effects with variables in the setjmp() calling function that were modified after the initial return.

longjmp() does not call destructors of any created objects. As such, it has been superseded with the C++ exception system, which uses thethrow andcatch keywords.

Related topics
setjmp

qsort

[edit |edit source]
Syntax
#include<cstdlib>void*qsort(constvoid*base,size_tnum,size_tsize,int(*compare)(constvoid*,constvoid*));

The function qsort() performs aQuick sort on an array. Note that some implementations may instead use a more efficient sorting algorithm.

*base refers to the array being sorted. This array containsnum elements, each of sizesize.

Thecompare function accepts two pointers to the object within the array - which need to first be cast to the object type being examined. The function returns -1 if the first parameter should be before the second, 1 if the first parameter is after, or 0 if the object matches.

Related topics
bsearch

raise

[edit |edit source]
Syntax
#include<csignal>intraise(int)

The raise() function raises a signal specified by its parameter.

If unsuccessful, it returns a non-zero value.

Related topics
signal

rand

[edit |edit source]
Syntax
#include<cstdlib>intrand(void);

The function rand() returns a pseudo-random integer between zero andRAND_MAX. An example:

srand(time(NULL));for(i=0;i<10;i++)printf("Random number #%d: %d\n",i,rand());

The rand() function must be seeded before its first call with thesrand() function - otherwise it will consistently return the same numbers when the program is restarted.

Note:
The generation ofrandom numbers is essential tocryptography. Anystochastic process (generation of random numbers) simulated by a computer, however, is not truly random, but pseudorandom; that is, the randomness of a computer is not from random radioactive decay of an unstable chemical isotope, but from predefined stochastic process, this is why this function needs to be seeded.


Related topics
srand

setjmp

[edit |edit source]
Syntax
#include<csetjmp>intsetjmp(jmp_bufenv);

The function setjmp() stores the current execution status inenv, and returns 0. The execution state includes basic information about which code is being executed in preparation for the longjmp() function call. If and when longjmp is called, setjmp() will return the parameter provided by longjmp - however, on the second return, variables that were modified after the initial setjmp() call may have an undefined value.

The buffer is only valid until the calling function returns, even if it is declared statically.

Since setjmp() does not understand constructors or destructors, it has been superseded with the C++ exception system, which uses thethrow andcatch keywords.

Note:
setjmp does not appear to be within thestd namespace.


Related topics
longjmp

signal

[edit |edit source]
Syntax
#include<csignal>void(*signal(intsig,void(*handler)(int)))(int)

The signal() function takes two parameters - the first is the signal identifier, and the second is a function pointer to a signal handler that takes one parameter. The return value of signal is a function pointer to the previous handler (or SIG_ERR if there was an error changing the signal handler).

By default, most raised signals are handled either by the handlers SIG_DFL (which is the default signal handler that usually shuts down the program), or SIG_IGN (which ignores the signal and continues program execution.)

When you specify a custom handler and the signal is raised, the signal handler reverts to the default.

While the signal handlers are superseded bythrow andcatch, some systems may still require you to use these functions to handle some important events. For example, the signal SIGTERM on Unix-based systems indicates that the program should terminate soon.

Note:
List of standard signals in Solaris
SIGHUP, SIGINT, SIGQUIT, SIGILL, SIGTRAP, SIGABRT, SIGEMT, SIGFPE, SIGKILL, SIGBUS, SIGSEGV, SIGSYS, SIGPIPE, SIGALRM, SIGTERM, SIGUSR1, SIGUSR2, SIGCHLD, SIGPWR, SIGWINCH, SIGURG, SIGIO, SIGSTOP, SIGTSTP, SIGCONT, SIGTTIN, SIGTTOU, SIGVTALRM, SIGPROF, SIGXCPU, SIGXFSZ, SIGWAITING, SIGLWP, SIGFREEZE, SIGTHAW, SIGCANCEL, SIGLOST


Related topics
raise

srand

[edit |edit source]
Syntax
#include<cstdlib>voidsrand(unsignedseed);

The function srand() is used to seed the random sequence generated byrand(). For any givenseed,rand() will generate a specific "random" sequence over and over again.

srand(time(NULL));for(i=0;i<10;i++)printf("Random number #%d: %d\n",i,rand());
Related topics
rand
(Standard C Time & Date functions)time

system

[edit |edit source]
Syntax
#include<cstdlib>intsystem(constchar*command);

The system() function runs the given command by passing it to the default command interpreter.

The return value is usually zero if the command executed without errors. If command isNULL, system() will test to see if there is a command interpreter available. Non-zero will be returned if there is a command interpreter available, zero if not.

Related topics
exit -getenv

va_arg

[edit |edit source]
Syntax
#include<cstdarg>typeva_arg(va_listargptr,type);voidva_end(va_listargptr);voidva_start(va_listargptr,last_parm);

The va_arg() macros are used to pass a variable number of arguments to a function.

  1. First, you must have a call to va_start() passing a validva_list and the name of the last argument variable before the ellipsis ("..."). This first argument can be anything; one way to use it is to have it be an integer describing the number of parameters being passed.
  2. Next, you call va_arg() passing theva_list and the type of the argument to be returned. The return value of va_arg() is the current parameter.
  3. Repeat calls to va_arg() for however many arguments you have.
  4. Finally, a call to va_end() passing theva_list is necessary for proper cleanup.
intsum(intnum,...){intanswer=0;va_listargptr;va_start(argptr,num);for(;num>0;num--){answer+=va_arg(argptr,int);}va_end(argptr);return(answer);}intmain(void){intanswer=sum(4,4,3,2,1);printf("The answer is %d\n",answer);return(0);}

This code displays 10, which is 4+3+2+1.

Here is another example of variable argument function, which is a simple printing function:

voidmy_printf(char*format,...){va_listargptr;va_start(argptr,format);while(*format!='\0'){// stringif(*format=='s'){char*s=va_arg(argptr,char*);printf("Printing a string: %s\n",s);}// characterelseif(*format=='c'){charc=(char)va_arg(argptr,int);printf("Printing a character: %c\n",c);break;}// integerelseif(*format=='d'){intd=va_arg(argptr,int);printf("Printing an integer: %d\n",d);}*format++;}va_end(argptr);}intmain(void){my_printf("sdc","This is a string",29,'X');return(0);}

This code displays the following output when run:

Printing a string: This is a stringPrinting an integer: 29Printing a character: X
Retrieved from "https://en.wikibooks.org/w/index.php?title=C%2B%2B_Programming/Code/Standard_C_Library/Other&oldid=1499573"
Category:

[8]ページ先頭

©2009-2025 Movatter.jp