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

From Wikibooks, open books for an open world
Jump to navigation Jump to search

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>
void abort( 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 catch SIGABRT) or failed abort.

SIGABRT is sent by the process to itself when it calls the abort libc function, defined in cstdlib. The SIGABRT 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>
int atexit( 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( const void *key, const void *base, size_t num, size_t size, int (*compare)(const void *, const void *));

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

*key refers to an object that matches an item searched within *base. This array contains num elements, each of size size.

The compare 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>
void exit( int exit_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( const char *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>
void longjmp( jmp_buf env, int val );

The function longjmp() behaves as a cross-function goto statement: it moves the point of execution to the record found in env, and causes setjmp() to return val. 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 the throw and catch keywords.

Related topics
setjmp

qsort[edit | edit source]

Syntax
#include <cstdlib>
void* qsort( const void *base, size_t num, size_t size, int (*compare)(const void *, const void *));

The function qsort() performs a Quick 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 contains num elements, each of size size.

The compare 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>
int raise(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>
int rand( void );

The function rand() returns a pseudo-random integer between zero and RAND_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 the srand() function - otherwise it will consistently return the same numbers when the program is restarted.

Note:
The generation of random numbers is essential to cryptography. Any stochastic 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>
int setjmp( jmp_buf env );

The function setjmp() stores the current execution status in env, 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 the throw and catch keywords.

Note:
setjmp does not appear to be within the std namespace.

Related topics
longjmp

signal[edit | edit source]

Syntax
#include <csignal>
void (*signal( int sig, 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 by throw and catch, 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>
void srand( unsigned seed );

The function srand() is used to seed the random sequence generated by rand(). For any given seed, 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>
int system( const char *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 is NULL, 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>
type va_arg( va_list argptr, type );
void va_end( va_list argptr );
void va_start( va_list argptr, 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 valid va_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 the va_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 the va_list is necessary for proper cleanup.
int sum( int num, ... ) {
  int answer = 0;
  va_list argptr;            

  va_start( argptr, num );            

  for( ; num > 0; num-- ) {
    answer += va_arg( argptr, int );
  }           

  va_end( argptr );           

  return( answer );
}             
                

int main( void ) {            

  int answer = 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:

void my_printf( char *format, ... ) {
  va_list argptr;             

  va_start( argptr, format );          

  while( *format != '\0' ) {
    // string
    if( *format == 's' ) {
      char* s = va_arg( argptr, char * );
      printf( "Printing a string: %s\n", s );
    }
    // character
    else if( *format == 'c' ) {
      char c = (char) va_arg( argptr, int );
      printf( "Printing a character: %c\n", c );
      break;
    }
    // integer
    else if( *format == 'd' ) {
      int d = va_arg( argptr, int );
      printf( "Printing an integer: %d\n", d );
    }          

    *format++;
  }            

  va_end( argptr );
}              
                

int main( 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 string
Printing an integer: 29
Printing a character: X