9. The value of timeptr->tm_min as if printed using the fprintf format "%.2d".
10. The character colon.
11. The value of timeptr->tm_sec as if printed using the fprintf format "%.2d".
12. The character space.
13. The value of timeptr->tm_year + 1900 as if printed using the fprintf format "%4d".
14. The character new line.
15. The null character.
Recommended practice
The strftime function allows more flexible formatting and supports locale-specific behavior. If you
do not require the exact form of the result string produced by the asctime_s function, consider
using the strftime function instead.
Returns
5 The asctime_s function returns zero if the time was successfully converted and stored into the
array pointed to by s. Otherwise, it returns a nonzero value.
K.<IP_ADDRESS> [The ctime_s function]
1 Synopsis
#define __STDC_WANT_LIB_EXT1__ 1
#include <time.h>
errno_t ctime_s(char *s, rsize_t maxsize, const time_t *timer);
Runtime-constraints
2 Neither s nor timer shall be a null pointer. maxsize shall not be less than 26 and shall not be greater
than RSIZE_MAX.
3 If there is a runtime-constraint violation, s[0] is set to a null character if s is not a null pointer and
maxsize is not equal zero and is not greater than RSIZE_MAX.
Description
4 The ctime_s function converts the calendar time pointed to by timer to local time in the form of a
string. It is equivalent to
asctime_s(s, maxsize, localtime_s(timer, &(struct tm){ 0 }))
Recommended practice
The strftime function allows more flexible formatting and supports locale-specific behavior. If you
do not require the exact form of the result string produced by the ctime_s function, consider using
the strftime function instead.
Returns
5 The ctime_s function returns zero if the time was successfully converted and stored into the array
pointed to by s. Otherwise, it returns a nonzero value.
K.<IP_ADDRESS> [The gmtime_s function]
1 Synopsis
#define __STDC_WANT_LIB_EXT1__ 1
#include <time.h>
struct tm *gmtime_s(const time_t * restrict timer, struct tm * restrict result);
Runtime-constraints
2 Neither timer nor result shall be a null pointer.
3 If there is a runtime-constraint violation, there is no attempt to convert the time.
Description
4 The gmtime_s function converts the calendar time pointed to by timer into a broken-down time,
expressed as UTC. The broken-down time is stored in the structure pointed to by result.
Returns
5 The gmtime_s function returns result, or a null pointer if the specified time cannot be converted to
UTC or there is a runtime-constraint violation.
K.<IP_ADDRESS> [The localtime_s function]
1 Synopsis
#define __STDC_WANT_LIB_EXT1__ 1
#include <time.h>
struct tm *localtime_s(const time_t *restrict timer, struct tm *restrict result);
Runtime-constraints
2 Neither timer nor result shall be a null pointer.
3 If there is a runtime-constraint violation, there is no attempt to convert the time.
Description
4 The localtime_s function converts the calendar time pointed to by timer into a broken-down time,
expressed as local time. The broken-down time is stored in the structure pointed to by result.
Returns
5 The localtime_s function returns result, or a null pointer if the specified time cannot be converted
to local time or there is a runtime-constraint violation.
K.3.9 [Extended multibyte and wide character utilities <wchar.h>]
1 The header <wchar.h> defines two types.
2 The types are
errno_t
which is type int; and
rsize_t
which is the type size_t.
3 Unless explicitly stated otherwise, if the execution of a function described in this subclause causes
copying to take place between objects that overlap, the objects take on unspecified values.
K.3.9.1 [Formatted wide character input/output functions]
K.<IP_ADDRESS> [The fwprintf_s function]
1 Synopsis
#define __STDC_WANT_LIB_EXT1__ 1
#include <wchar.h>
int fwprintf_s(FILE * restrict stream, const wchar_t * restrict format, ...);
Runtime-constraints
2 Neither stream nor format shall be a null pointer. The %n specifier[517] (modified or not by flags,
field width, or precision) shall not appear in the wide string pointed to by format. Any argument to
fwprintf_s corresponding to a %s specifier shall not be a null pointer.
Footnote 517) It is not a runtime-constraint violation for the wide characters %n to appear in sequence in the wide string pointed at
by format when those wide characters are not a interpreted as a %n specifier. For example, if the entire format string was
L"%%n".
3 If there is a runtime-constraint violation, the fwprintf_s function does not attempt to produce
further output, and it is unspecified to what extent fwprintf_s produced output before discovering
the runtime-constraint violation.
Description
4 The fwprintf_s function is equivalent to the fwprintf function except for the explicit runtime-
constraints listed above.
Returns
5 The fwprintf_s function returns the number of wide characters transmitted, or a negative value if
an output error, encoding error, or runtime-constraint violation occurred.
K.<IP_ADDRESS> [The fwscanf_s function]
1 Synopsis
#define __STDC_WANT_LIB_EXT1__ 1
#include <stdio.h>
#include <wchar.h>
int fwscanf_s(FILE * restrict stream, const wchar_t * restrict format, ...);
Runtime-constraints
2 Neither stream nor format shall be a null pointer. Any argument indirected though in order to
store converted input shall not be a null pointer.
3 If there is a runtime-constraint violation, the fwscanf_s function does not attempt to perform
further input, and it is unspecified to what extent fwscanf_s performed input before discovering
the runtime-constraint violation.
Description
4 The fwscanf_s function is equivalent to fwscanf except that the c, s, and [ conversion specifiers
apply to a pair of arguments (unless assignment suppression is indicated by a *). The first of these
arguments is the same as for fwscanf. That argument is immediately followed in the argument
list by the second argument, which has type size_t and gives the number of elements in the array
pointed to by the first argument of the pair. If the first argument points to a scalar object, it is
considered to be an array of one element.[518]
Footnote 518) If the format is known at translation time, an implementation can issue a diagnostic for any argument used to store
the result from a c, s, or [ conversion specifier if that argument is not followed by an argument of a type compatible with
rsize_t. A limited amount of checking can be done if even if the format is not known at translation time. For example, an
implementation could issue a diagnostic for each argument after format that has of type pointer to one of char, signed char,
unsigned char, or void that is not followed by an argument of a type compatible with rsize_t. The diagnostic could warn
that unless the pointer is being used with a conversion specifier using the hh length modifier, a length argument is expected
to follow the pointer argument. Another useful diagnostic could flag any non-pointer argument following format that did
not have a type compatible with rsize_t.
5 A matching failure occurs if the number of elements in a receiving object is insufficient to hold the
converted input (including any trailing null character).
Returns
6 The fwscanf_s function returns the value of the macro EOF if an input failure occurs before any
conversion or if there is a runtime-constraint violation. Otherwise, the fwscanf_s function returns
the number of input items assigned, which can be fewer than provided for, or even zero, in the event
of an early matching failure.
K.<IP_ADDRESS> [The snwprintf_s function]
1 Synopsis
#define __STDC_WANT_LIB_EXT1__ 1
#include <wchar.h>
int snwprintf_s(wchar_t * restrict s, rsize_t n, const wchar_t * restrict format,
...);
Runtime-constraints
2 Neither s nor format shall be a null pointer. n shall neither equal zero nor be greater than
RSIZE_MAX/sizeof(wchar_t). The %n specifier[519] (modified or not by flags, field width, or pre-
cision) shall not appear in the wide string pointed to by format. Any argument to snwprintf_s
corresponding to a %s specifier shall not be a null pointer. No encoding error shall occur.
Footnote 519) It is not a runtime-constraint violation for the wide characters %n to appear in sequence in the wide string pointed at
by format when those wide characters are not a interpreted as a %n specifier. For example, if the entire format string was
L"%%n".
3 If there is a runtime-constraint violation, then if s is not a null pointer and n is greater than zero
and not greater than RSIZE_MAX/sizeof(wchar_t), then the snwprintf_s function sets s[0] to
the null wide character.
Description
4 The snwprintf_s function is equivalent to the swprintf function except for the explicit runtime-
constraints listed above.
5 The snwprintf_s function, unlike swprintf_s, will truncate the result to fit within the array pointed
to by s.
Returns
6 The snwprintf_s function returns the number of wide characters that would have been written
had n been sufficiently large, not counting the terminating wide null character, or a negative value
if a runtime-constraint violation occurred. Thus, the null-terminated output has been completely
written if and only if the returned value is both nonnegative and less than n.
K.<IP_ADDRESS> [The swprintf_s function]
1 Synopsis
#define __STDC_WANT_LIB_EXT1__ 1
#include <wchar.h>
int swprintf_s(wchar_t * restrict s, rsize_t n, const wchar_t * restrict format,
...);
Runtime-constraints
2 Neither s nor format shall be a null pointer. n shall neither equal zero nor be greater than
RSIZE_MAX/sizeof(wchar_t). The number of wide characters (including the trailing null) required
for the result to be written to the array pointed to by s shall not be greater than n. The %n specifier[520]
(modified or not by flags, field width, or precision) shall not appear in the wide string pointed to by
format. Any argument to swprintf_s corresponding to a %s specifier shall not be a null pointer.
No encoding error shall occur.
Footnote 520) It is not a runtime-constraint violation for the wide characters %n to appear in sequence in the wide string pointed at
by format when those wide characters are not a interpreted as a %n specifier. For example, if the entire format string was
L"%%n".
3 If there is a runtime-constraint violation, then if s is not a null pointer and n is greater than zero and
not greater than RSIZE_MAX/sizeof(wchar_t), then the swprintf_s function sets s[0] to the null
wide character.
Description
4 The swprintf_s function is equivalent to the swprintf function except for the explicit runtime-
constraints listed above.
5 The swprintf_s function, unlike snwprintf_s, treats a result too big for the array pointed to by s
as a runtime-constraint violation.
Returns
6 If no runtime-constraint violation occurred, the swprintf_s function returns the number of wide
characters written in the array, not counting the terminating null wide character. If an encoding
error occurred or if n or more wide characters are requested to be written, swprintf_s returns a
negative value. If any other runtime-constraint violation occurred, swprintf_s returns zero.
K.<IP_ADDRESS> [The swscanf_s function]
1 Synopsis
#define __STDC_WANT_LIB_EXT1__ 1
#include <wchar.h>
int swscanf_s(const wchar_t * restrict s, const wchar_t * restrict format, ...);
Runtime-constraints
2 Neither s nor format shall be a null pointer. Any argument indirected though in order to store
converted input shall not be a null pointer.
3 If there is a runtime-constraint violation, the swscanf_s function does not attempt to perform
further input, and it is unspecified to what extent swscanf_s performed input before discovering
the runtime-constraint violation.
Description
4 The swscanf_s function is equivalent to fwscanf_s, except that the argument s specifies a wide
string from which the input is to be obtained, rather than from a stream. Reaching the end of the
wide string is equivalent to encountering end-of-file for the fwscanf_s function.
Returns
5 The swscanf_s function returns the value of the macro EOF if an input failure occurs before any
conversion or if there is a runtime-constraint violation. Otherwise, the swscanf_s function returns
the number of input items assigned, which can be fewer than provided for, or even zero, in the event
of an early matching failure.
K.<IP_ADDRESS> [The vfwprintf_s function]
1 Synopsis
#define __STDC_WANT_LIB_EXT1__ 1
#include <stdarg.h>
#include <stdio.h>
#include <wchar.h>
int vfwprintf_s(FILE * restrict stream, const wchar_t * restrict format,
va_list arg);
Runtime-constraints
2 Neither stream nor format shall be a null pointer. The %n specifier[521] (modified or not by flags,
field width, or precision) shall not appear in the wide string pointed to by format. Any argument to
vfwprintf_s corresponding to a %s specifier shall not be a null pointer.
Footnote 521) It is not a runtime-constraint violation for the wide characters %n to appear in sequence in the wide string pointed at
by format when those wide characters are not a interpreted as a %n specifier. For example, if the entire format string was
L"%%n".
3 If there is a runtime-constraint violation, the vfwprintf_s function does not attempt to produce
further output, and it is unspecified to what extent vfwprintf_s produced output before discovering
the runtime-constraint violation.
Description
4 The vfwprintf_s function is equivalent to the vfwprintf function except for the explicit runtime-
constraints listed above.
Returns
5 The vfwprintf_s function returns the number of wide characters transmitted, or a negative value if
an output error, encoding error, or runtime-constraint violation occurred.
K.<IP_ADDRESS> [The vfwscanf_s function]
1 Synopsis
#define __STDC_WANT_LIB_EXT1__ 1
#include <stdarg.h>
#include <stdio.h>
#include <wchar.h>
int vfwscanf_s(FILE * restrict stream, const wchar_t * restrict format,
va_list arg);
Runtime-constraints
2 Neither stream nor format shall be a null pointer. Any argument indirected though in order to
store converted input shall not be a null pointer.
3 If there is a runtime-constraint violation, the vfwscanf_s function does not attempt to perform
further input, and it is unspecified to what extent vfwscanf_s performed input before discovering
the runtime-constraint violation.
Description
4 The vfwscanf_s function is equivalent to fwscanf_s, with the variable argument list replaced by
arg, which shall have been initialized by the va_start macro (and possibly subsequent va_arg
calls). The vfwscanf_s function does not invoke the va_end macro[522] .
Returns
Footnote 522) As the functions vfwscanf_s , vwscanf_s , and vswscanf_s invoke the va_arg macro, the representation of arg after the
return is indeterminate.
5 The vfwscanf_s function returns the value of the macro EOF if an input failure occurs before any
conversion or if there is a runtime-constraint violation. Otherwise, the vfwscanf_s function returns
the number of input items assigned, which can be fewer than provided for, or even zero, in the event
of an early matching failure.
K.<IP_ADDRESS> [The vsnwprintf_s function]
1 Synopsis
#define __STDC_WANT_LIB_EXT1__ 1
#include <stdarg.h>
#include <wchar.h>
int vsnwprintf_s(wchar_t *restrict s, rsize_t n, const wchar_t *restrict format,
va_list arg);
Runtime-constraints
2 Neither s nor format shall be a null pointer. n shall neither equal zero nor be greater than
RSIZE_MAX/sizeof(wchar_t). The %n specifier[523] (modified or not by flags, field width, or preci-
sion) shall not appear in the wide string pointed to by format. Any argument to vsnwprintf_s
corresponding to a %s specifier shall not be a null pointer. No encoding error shall occur.
Footnote 523) It is not a runtime-constraint violation for the wide characters %n to appear in sequence in the wide string pointed at
by format when those wide characters are not a interpreted as a %n specifier. For example, if the entire format string was
L"%%n".
3 If there is a runtime-constraint violation, then if s is not a null pointer and n is greater than zero and
not greater than RSIZE_MAX/sizeof(wchar_t), then the vsnwprintf_s function sets s[0] to the
null wide character.
Description
4 The vsnwprintf_s function is equivalent to the vswprintf function except for the explicit runtime-
constraints listed above.
5 The vsnwprintf_s function, unlike vswprintf_s, will truncate the result to fit within the array
pointed to by s.
Returns
6 The vsnwprintf_s function returns the number of wide characters that would have been written
had n been sufficiently large, not counting the terminating null character, or a negative value if
a runtime-constraint violation occurred. Thus, the null-terminated output has been completely
written if and only if the returned value is both nonnegative and less than n.
K.<IP_ADDRESS> [The vswprintf_s function]
1 Synopsis
#define __STDC_WANT_LIB_EXT1__ 1
#include <stdarg.h>
#include <wchar.h>
int vswprintf_s(wchar_t *restrict s, rsize_t n, const wchar_t *restrict format,
va_list arg);
Runtime-constraints
2 Neither s nor format shall be a null pointer. n shall neither equal zero nor be greater than
RSIZE_MAX/sizeof(wchar_t). The number of wide characters (including the trailing null) required
for the result to be written to the array pointed to by s shall not be greater than n. The %n specifier[524]
(modified or not by flags, field width, or precision) shall not appear in the wide string pointed to by
format. Any argument to vswprintf_s corresponding to a %s specifier shall not be a null pointer.
No encoding error shall occur.
Footnote 524) It is not a runtime-constraint violation for the wide characters %n to appear in sequence in the wide string pointed at
by format when those wide characters are not a interpreted as a %n specifier. For example, if the entire format string was
L"%%n".
3 If there is a runtime-constraint violation, then if s is not a null pointer and n is greater than zero
and not greater than RSIZE_MAX/sizeof(wchar_t), then the vswprintf_s function sets s[0] to
the null wide character.
Description
4 The vswprintf_s function is equivalent to the vswprintf function except for the explicit runtime-
constraints listed above.
5 The vswprintf_s function, unlike vsnwprintf_s, treats a result too big for the array pointed to by
s as a runtime-constraint violation.
Returns
6 If no runtime-constraint violation occurred, the vswprintf_s function returns the number of wide
characters written in the array, not counting the terminating null wide character. If an encoding
error occurred or if n or more wide characters are requested to be written, vswprintf_s returns a
negative value. If any other runtime-constraint violation occurred, vswprintf_s returns zero.
K.<IP_ADDRESS> [The vswscanf_s function]
1 Synopsis
#define __STDC_WANT_LIB_EXT1__ 1
#include <stdarg.h>
#include <wchar.h>
int vswscanf_s(const wchar_t * restrict s, const wchar_t * restrict format,
va_list arg);
Runtime-constraints
2 Neither s nor format shall be a null pointer. Any argument indirected though in order to store
converted input shall not be a null pointer.
3 If there is a runtime-constraint violation, the vswscanf_s function does not attempt to perform
further input, and it is unspecified to what extent vswscanf_s performed input before discovering
the runtime-constraint violation.
Description
4 The vswscanf_s function is equivalent to swscanf_s, with the variable argument list replaced by
arg, which shall have been initialized by the va_start macro (and possibly subsequent va_arg
calls). The vswscanf_s function does not invoke the va_end macro[525] .
Returns
Footnote 525) As the functions vfwscanf_s , vwscanf_s , and vswscanf_s invoke the va_arg macro, the representation of arg after the
return is indeterminate.
5 The vswscanf_s function returns the value of the macro EOF if an input failure occurs before any
conversion or if there is a runtime-constraint violation. Otherwise, the vswscanf_s function returns
the number of input items assigned, which can be fewer than provided for, or even zero, in the event
of an early matching failure.
K.<IP_ADDRESS> [The vwprintf_s function]
1 Synopsis
#define __STDC_WANT_LIB_EXT1__ 1
#include <stdarg.h>
#include <wchar.h>
int vwprintf_s(const wchar_t * restrict format, va_list arg);
Runtime-constraints
2 format shall not be a null pointer. The %n specifier[526] (modified or not by flags, field width, or
precision) shall not appear in the wide string pointed to by format. Any argument to vwprintf_s
corresponding to a %s specifier shall not be a null pointer.
Footnote 526) It is not a runtime-constraint violation for the wide characters %n to appear in sequence in the wide string pointed at
by format when those wide characters are not a interpreted as a %n specifier. For example, if the entire format string was
L"%%n".
3 If there is a runtime-constraint violation, the vwprintf_s function does not attempt to produce
further output, and it is unspecified to what extent vwprintf_s produced output before discovering
the runtime-constraint violation.
Description
4 The vwprintf_s function is equivalent to the vwprintf function except for the explicit runtime-
constraints listed above.
Returns
5 The vwprintf_s function returns the number of wide characters transmitted, or a negative value if
an output error, encoding error, or runtime-constraint violation occurred.
K.<IP_ADDRESS> [The vwscanf_s function]
1 Synopsis
#define __STDC_WANT_LIB_EXT1__ 1
#include <stdarg.h>
#include <wchar.h>
int vwscanf_s(const wchar_t * restrict format, va_list arg);
Runtime-constraints
2 format shall not be a null pointer. Any argument indirected though in order to store converted
input shall not be a null pointer.
3 If there is a runtime-constraint violation, the vwscanf_s function does not attempt to perform
further input, and it is unspecified to what extent vwscanf_s performed input before discovering
the runtime-constraint violation.
Description
4 The vwscanf_s function is equivalent to wscanf_s, with the variable argument list replaced by arg,
which shall have been initialized by the va_start macro (and possibly subsequent va_arg calls).
The vwscanf_s function does not invoke the va_end macro[527] .
Returns
Footnote 527) As the functions vfwscanf_s , vwscanf_s , and vswscanf_s invoke the va_arg macro, the representation of arg after the
return is indeterminate.
5 The vwscanf_s function returns the value of the macro EOF if an input failure occurs before any
conversion or if there is a runtime-constraint violation. Otherwise, the vwscanf_s function returns
the number of input items assigned, which can be fewer than provided for, or even zero, in the event
of an early matching failure.
K.<IP_ADDRESS> [The wprintf_s function]
1 Synopsis
#define __STDC_WANT_LIB_EXT1__ 1
#include <wchar.h>
int wprintf_s(const wchar_t * restrict format, ...);
Runtime-constraints
2 format shall not be a null pointer. The %n specifier[528] (modified or not by flags, field width, or
precision) shall not appear in the wide string pointed to by format. Any argument to wprintf_s
corresponding to a %s specifier shall not be a null pointer.
Footnote 528) It is not a runtime-constraint violation for the wide characters %n to appear in sequence in the wide string pointed at
by format when those wide characters are not a interpreted as a %n specifier. For example, if the entire format string was
L"%%n".
3 If there is a runtime-constraint violation, the wprintf_s function does not attempt to produce
further output, and it is unspecified to what extent wprintf_s produced output before discovering
the runtime-constraint violation.
Description
4 The wprintf_s function is equivalent to the wprintf function except for the explicit runtime-
constraints listed above.
Returns
5 The wprintf_s function returns the number of wide characters transmitted, or a negative value if
an output error, encoding error, or runtime-constraint violation occurred.
K.<IP_ADDRESS> [The wscanf_s function]
1 Synopsis
#define __STDC_WANT_LIB_EXT1__ 1
#include <wchar.h>
int wscanf_s(const wchar_t * restrict format, ...);
Runtime-constraints
2 format shall not be a null pointer. Any argument indirected though in order to store converted
input shall not be a null pointer.
3 If there is a runtime-constraint violation, the wscanf_s function does not attempt to perform further
input, and it is unspecified to what extent wscanf_s performed input before discovering the runtime-
constraint violation.
Description
4 The wscanf_s function is equivalent to fwscanf_s with the argument stdin interposed before the
arguments to wscanf_s.
Returns
5 The wscanf_s function returns the value of the macro EOF if an input failure occurs before any
conversion or if there is a runtime-constraint violation. Otherwise, the wscanf_s function returns
the number of input items assigned, which can be fewer than provided for, or even zero, in the event
of an early matching failure.
K.3.9.2 [General wide string utilities]
K.<IP_ADDRESS> [Wide string copying functions]
K.<IP_ADDRESS>.1 [The wcscpy_s function]
1 Synopsis
#define __STDC_WANT_LIB_EXT1__ 1
#include <wchar.h>
errno_t wcscpy_s(wchar_t *restrict s1, rsize_t s1max,
const wchar_t *restrict s2);
Runtime-constraints
2 Neither s1 nor s2 shall be a null pointer. s1max shall not be greater than
RSIZE_MAX/sizeof(wchar_t). s1max shall not equal zero. s1max shall be greater than
wcsnlen_s(s2, s1max) . Copying shall not take place between objects that overlap.
3 If there is a runtime-constraint violation, then if s1 is not a null pointer and s1max is greater than
zero and not greater than RSIZE_MAX/sizeof(wchar_t), then wcscpy_s sets s1[0] to the null wide
character.
Description
4 The wcscpy_s function copies the wide string pointed to by s2 (including the terminating null wide
character) into the array pointed to by s1.
5 All elements following the terminating null wide character (if any) written by wcscpy_s in the array
of s1max wide characters pointed to by s1 take unspecified values when wcscpy_s returns.[529]
Returns
Footnote 529) This allows an implementation to copy wide characters from s2 to s1 while simultaneously checking if any of those wide
characters are null. Such an approach might write a wide character to every element of s1 before discovering that the first
element was set to the null wide character.
6 The wcscpy_s function returns zero[530] if there was no runtime-constraint violation. Otherwise, a
nonzero value is returned.
Footnote 530) A zero return value implies that all of the requested wide characters from the string pointed to by s2 fit within the array
pointed to by s1 and that the result in s1 is null terminated.
K.<IP_ADDRESS>.2 [The wcsncpy_s function]
1 Synopsis
#define __STDC_WANT_LIB_EXT1__ 1
#include <wchar.h>
errno_t wcsncpy_s(wchar_t * restrict s1, rsize_t s1max,
const wchar_t * restrict s2, rsize_t n);
Runtime-constraints
2 Neither s1 nor s2 shall be a null pointer. Neither s1max nor n shall be greater than
RSIZE_MAX/sizeof(wchar_t). s1max shall not equal zero. If n is not less than s1max, then
s1max shall be greater than wcsnlen_s(s2, s1max) . Copying shall not take place between objects
that overlap.
3 If there is a runtime-constraint violation, then if s1 is not a null pointer and s1max is greater than
zero and not greater than RSIZE_MAX/sizeof(wchar_t), then wcsncpy_s sets s1[0] to the null
wide character.
Description
4 The wcsncpy_s function copies not more than n successive wide characters (wide characters that
follow a null wide character are not copied) from the array pointed to by s2 to the array pointed to
by s1. If no null wide character was copied from s2, then s1[n] is set to a null wide character.
5 All elements following the terminating null wide character (if any) written by wcsncpy_s in the array
of s1max wide characters pointed to by s1 take unspecified values when wcsncpy_s returns.[531]
Returns
Footnote 531) This allows an implementation to copy wide characters from s2 to s1 while simultaneously checking if any of those wide
characters are null. Such an approach might write a wide character to every element of s1 before discovering that the first
element was set to the null wide character.
6 The wcsncpy_s function returns zero[532] if there was no runtime-constraint violation. Otherwise, a
nonzero value is returned.
Footnote 532) A zero return value implies that all of the requested wide characters from the string pointed to by s2 fit within the array
pointed to by s1 and that the result in s1 is null terminated.
7 EXAMPLE 1 The wcsncpy_s function can be used to copy a wide string without the danger that the result will not be null
terminated or that wide characters will be written past the end of the destination array.
#define __STDC_WANT_LIB_EXT1__ 1
#include <wchar.h>
/* ... */
wchar_t src1[100] = L"hello";
wchar_t src2[7] = {L’g’, L’o’, L’o’, L’d’, L’b’, L’y’, L’e’};
wchar_t dst1[6], dst2[5], dst3[5];
int r1, r2, r3;
r1 = wcsncpy_s(dst1, 6, src1, 100);
r2 = wcsncpy_s(dst2, 5, src2, 7);
r3 = wcsncpy_s(dst3, 5, src2, 4);
The first call will assign to r1 the value zero and to dst1 the sequence of wide characters hello\0.
The second call will assign to r2 a nonzero value and to dst2 the sequence of wide characters \0.
The third call will assign to r3 the value zero and to dst3 the sequence of wide characters good\0.
K.<IP_ADDRESS>.3 [The wmemcpy_s function]
1 Synopsis
#define __STDC_WANT_LIB_EXT1__ 1
#include <wchar.h>
errno_t wmemcpy_s(wchar_t *restrict s1, rsize_t s1max,
const wchar_t *restrict s2, rsize_t n);
Runtime-constraints
2 Neither s1 nor s2 shall be a null pointer. Neither s1max nor n shall be greater than
RSIZE_MAX/sizeof(wchar_t). n shall not be greater than s1max. Copying shall not take
place between objects that overlap.
3 If there is a runtime-constraint violation, the wmemcpy_s function stores zeros in the first s1max wide
characters of the object pointed to by s1 if s1 is not a null pointer and s1max is not greater than
RSIZE_MAX/sizeof(wchar_t).
Description
4 The wmemcpy_s function copies n successive wide characters from the object pointed to by s2 into
the object pointed to by s1.
Returns
5 The wmemcpy_s function returns zero if there was no runtime-constraint violation. Otherwise, a
nonzero value is returned.
K.<IP_ADDRESS>.4 [The wmemmove_s function]
1 Synopsis
#define __STDC_WANT_LIB_EXT1__ 1
#include <wchar.h>
errno_t wmemmove_s(wchar_t *s1, rsize_t s1max, const wchar_t *s2, rsize_t n);
Runtime-constraints
2 Neither s1 nor s2 shall be a null pointer. Neither s1max nor n shall be greater than
RSIZE_MAX/sizeof(wchar_t). n shall not be greater than s1max.
3 If there is a runtime-constraint violation, the wmemmove_s function stores zeros in the first s1max
wide characters of the object pointed to by s1 if s1 is not a null pointer and s1max is not greater than
RSIZE_MAX/sizeof(wchar_t).
Description
4 The wmemmove_s function copies n successive wide characters from the object pointed to by s2 into
the object pointed to by s1. This copying takes place as if the n wide characters from the object
pointed to by s2 are first copied into a temporary array of n wide characters that does not overlap
the objects pointed to by s1 or s2, and then the n wide characters from the temporary array are
copied into the object pointed to by s1.
Returns
5 The wmemmove_s function returns zero if there was no runtime-constraint violation. Otherwise, a
nonzero value is returned.
K.<IP_ADDRESS> [Wide string concatenation functions]
K.<IP_ADDRESS>.1 [The wcscat_s function]
1 Synopsis
#define __STDC_WANT_LIB_EXT1__ 1
#include <wchar.h>
errno_t wcscat_s(wchar_t * restrict s1, rsize_t s1max,
const wchar_t * restrict s2);
Runtime-constraints
2 Let m denote the value s1max - wcsnlen_s(s1, s1max) upon entry to wcscat_s.
3 Neither s1 nor s2 shall be a null pointer. s1max shall not be greater than
RSIZE_MAX/sizeof(wchar_t). s1max shall not equal zero. m shall not equal zero.[533] m
shall be greater than wcsnlen_s(s2, m). Copying shall not take place between objects that overlap.
Footnote 533) Zero means that s1 was not null terminated upon entry to wcscat_s .
4 If there is a runtime-constraint violation, then if s1 is not a null pointer and s1max is greater than
zero and not greater than RSIZE_MAX/sizeof(wchar_t), then wcscat_s sets s1[0] to the null wide
character.
Description
5 The wcscat_s function appends a copy of the wide string pointed to by s2 (including the terminating
null wide character) to the end of the wide string pointed to by s1. The initial wide character from
s2 overwrites the null wide character at the end of s1.
6 All elements following the terminating null wide character (if any) written by wcscat_s in the array
of s1max wide characters pointed to by s1 take unspecified values when wcscat_s returns.[534]
Returns
Footnote 534) This allows an implementation to append wide characters from s2 to s1 while simultaneously checking if any of those
wide characters are null. Such an approach might write a wide character to every element of s1 before discovering that the
first element was set to the null wide character.
7 The wcscat_s function returns zero[535] if there was no runtime-constraint violation. Otherwise, a
nonzero value is returned.
Footnote 535) A zero return value implies that all of the requested wide characters from the wide string pointed to by s2 were appended
to the wide string pointed to by s1 and that the result in s1 is null terminated.
K.<IP_ADDRESS>.2 [The wcsncat_s function]
1 Synopsis
#define __STDC_WANT_LIB_EXT1__ 1
#include <wchar.h>
errno_t wcsncat_s(wchar_t * restrict s1, rsize_t s1max,
const wchar_t * restrict s2, rsize_t n);
Runtime-constraints
2 Let m denote the value s1max - wcsnlen_s(s1, s1max) upon entry to wcsncat_s.
3 Neither s1 nor s2 shall be a null pointer. Neither s1max nor n shall be greater than
RSIZE_MAX/sizeof(wchar_t). s1max shall not equal zero. m shall not equal zero.[536] If n
is not less than m, then m shall be greater than wcsnlen_s(s2, m). Copying shall not take place
between objects that overlap.
Footnote 536) Zero means that s1 was not null terminated upon entry to wcsncat_s .
4 If there is a runtime-constraint violation, then if s1 is not a null pointer and s1max is greater than
zero and not greater than RSIZE_MAX/sizeof(wchar_t), then wcsncat_s sets s1[0] to the null
wide character.
Description
5 The wcsncat_s function appends not more than n successive wide characters (wide characters that
follow a null wide character are not copied) from the array pointed to by s2 to the end of the wide
string pointed to by s1. The initial wide character from s2 overwrites the null wide character at the
end of s1. If no null wide character was copied from s2, then s1[s1max- m +n] is set to a null wide
character.
6 All elements following the terminating null wide character (if any) written by wcsncat_s in the array
of s1max wide characters pointed to by s1 take unspecified values when wcsncat_s returns.[537]
Returns
Footnote 537) This allows an implementation to append wide characters from s2 to s1 while simultaneously checking if any of those
wide characters are null. Such an approach might write a wide character to every element of s1 before discovering that the
first element was set to the null wide character.
7 The wcsncat_s function returns zero[538] if there was no runtime-constraint violation. Otherwise, a
nonzero value is returned.
Footnote 538) A zero return value implies that all of the requested wide characters from the wide string pointed to by s2 were appended
to the wide string pointed to by s1 and that the result in s1 is null terminated.
8 EXAMPLE 1 The wcsncat_s function can be used to copy a wide string without the danger that the result will not be null
terminated or that wide characters will be written past the end of the destination array.
#define __STDC_WANT_LIB_EXT1__ 1
#include <wchar.h>
/* ... */
wchar_t s1[100] = L"good";
wchar_t s2[6] = L"hello";
wchar_t s3[6] = L"hello";
wchar_t s4[7] = L"abc";
wchar_t s5[1000] = L"bye";
int r1, r2, r3, r4;
r1 = wcsncat_s(s1, 100, s5, 1000);
r2 = wcsncat_s(s2, 6, L"", 1);
r3 = wcsncat_s(s3, 6, L"X", 2);
r4 = wcsncat_s(s4, 7, L"defghijklmn", 3);
After the first call r1 will have the value zero and s1 will be the wide character sequence goodbye\0.
After the second call r2 will have the value zero and s2 will be the wide character sequence hello\0.
After the third call r3 will have a nonzero value and s3 will be the wide character sequence \0.
After the fourth call r4 will have the value zero and s4 will be the wide character sequence abcdef\0.
K.<IP_ADDRESS> [Wide string search functions]
K.<IP_ADDRESS>.1 [The wcstok_s function]
1 Synopsis
#define __STDC_WANT_LIB_EXT1__ 1
#include <wchar.h>
wchar_t *wcstok_s(wchar_t * restrict s1, rsize_t * restrict s1max,
const wchar_t * restrict s2, wchar_t ** restrict ptr);
Runtime-constraints
2 None of s1max, s2, or ptr shall be a null pointer. If s1 is a null pointer, then *ptr shall not be a null
pointer. The value of *s1max shall not be greater than RSIZE_MAX/sizeof(wchar_t). The end of
the token found shall occur within the first *s1max wide characters of s1 for the first call, and shall
occur within the first *s1max wide characters of where searching resumes on subsequent calls.
3 If there is a runtime-constraint violation, the wcstok_s function does not indirect through the s1 or
s2 pointers, and does not store a value in the object pointed to by ptr.
Description
4 A sequence of calls to the wcstok_s function breaks the wide string pointed to by s1 into a sequence
of tokens, each of which is delimited by a wide character from the wide string pointed to by s2.
The fourth argument points to a caller-provided wchar_t pointer into which the wcstok_s function
stores information necessary for it to continue scanning the same wide string.
5 The first call in a sequence has a non-null first argument and s1max points to an object whose value
is the number of elements in the wide character array pointed to by the first argument. The first call
stores an initial value in the object pointed to by ptr and updates the value pointed to by s1max
to reflect the number of elements that remain in relation to ptr. Subsequent calls in the sequence
have a null first argument and the objects pointed to by s1max and ptr are required to have the
values stored by the previous call in the sequence, which are then updated. The separator wide
string pointed to by s2 may be different from call to call.
6 The first call in the sequence searches the wide string pointed to by s1 for the first wide character
that is not contained in the current separator wide string pointed to by s2. If no such wide character
is found, then there are no tokens in the wide string pointed to by s1 and the wcstok_s function
returns a null pointer. If such a wide character is found, it is the start of the first token.
7 The wcstok_s function then searches from there for the first wide character in s1 that is contained
in the current separator wide string. If no such wide character is found, the current token extends
to the end of the wide string pointed to by s1, and subsequent searches in the same wide string
for a token return a null pointer. If such a wide character is found, it is overwritten by a null wide
character, which terminates the current token.
8 In all cases, the wcstok_s function stores sufficient information in the pointer pointed to by ptr so
that subsequent calls, with a null pointer for s1 and the unmodified pointer value for ptr, shall start
searching just past the element overwritten by a null wide character (if any).
Returns
9 The wcstok_s function returns a pointer to the first wide character of a token, or a null pointer if
there is no token or there is a runtime-constraint violation.
10 EXAMPLE
#define __STDC_WANT_LIB_EXT1__ 1
#include <wchar.h>
static wchar_t str1[] = L"?a???b,,,#c";
static wchar_t str2[] = L"\t \t";
wchar_t *t, *ptr1, *ptr2;
rsize_t max1 = wcslen(str1)+1;
rsize_t max2 = wcslen(str2)+1;
t = wcstok_s(str1, &max1, "?", &ptr1); // t points to the token "a"
t = wcstok_s(NULL, &max1, ",", &ptr1); // t points to the token "??b"
t = wcstok_s(str2, &max2, " \t", &ptr2); // t is a null pointer
t = wcstok_s(NULL, &max1, "#,", &ptr1); // t points to the token "c"
t = wcstok_s(NULL, &max1, "?", &ptr1); // t is a null pointer
K.<IP_ADDRESS> [Miscellaneous functions]
K.<IP_ADDRESS>.1 [The wcsnlen_s function]
1 Synopsis
#define __STDC_WANT_LIB_EXT1__ 1
#include <wchar.h>
size_t wcsnlen_s(const wchar_t *s, size_t maxsize);
Description
2 The wcsnlen_s function computes the length of the wide string pointed to by s.
Returns
3 If s is a null pointer,[539] then the wcsnlen_s function returns zero.
Footnote 539) Note that the wcsnlen_s function has no runtime-constraints. This lack of runtime-constraints along with the values
returned for a null pointer or an unterminated wide string argument make wcsnlen_s useful in algorithms that gracefully
handle such exceptional data.
4 Otherwise, the wcsnlen_s function returns the number of wide characters that precede the termi-
nating null wide character. If there is no null wide character in the first maxsize wide characters of
s then wcsnlen_s returns maxsize. At most the first maxsize wide characters of s shall be accessed
by wcsnlen_s.
K.3.9.3 [Extended multibyte/wide character conversion utilities]
K.<IP_ADDRESS> [Restartable multibyte/wide character conversion functions]
1 Unlike wcrtomb, wcrtomb_s does not permit the ps parameter (the pointer to the conversion state)
to be a null pointer.
K.<IP_ADDRESS>.1 [The wcrtomb_s function]
1 Synopsis
#include <wchar.h>
errno_t wcrtomb_s(size_t * restrict retval, char * restrict s, rsize_t smax,
wchar_t wc, mbstate_t * restrict ps);
Runtime-constraints
2 Neither retval nor ps shall be a null pointer. If s is not a null pointer, then smax shall not equal
zero and shall not be greater than RSIZE_MAX. If s is not a null pointer, then smax shall be not be less
than the number of bytes to be stored in the array pointed to by s. If s is a null pointer, then smax
shall equal zero.
3 If there is a runtime-constraint violation, then wcrtomb_s does the following. If s is not a null pointer
and smax is greater than zero and not greater than RSIZE_MAX, then wcrtomb_s sets s[0] to the null
character. If retval is not a null pointer, then wcrtomb_s sets *retval to (size_t)(-1) .
Description
4 If s is a null pointer, the wcrtomb_s function is equivalent to the call
wcrtomb_s(&retval, buf, sizeof buf, L’\0’, ps)
where retval and buf are internal variables of the appropriate types, and the size of buf is greater
than MB_CUR_MAX.
5 If s is not a null pointer, the wcrtomb_s function determines the number of bytes needed to represent
the multibyte character that corresponds to the wide character given by wc (including any shift
sequences), and stores the multibyte character representation in the array whose first element is
pointed to by s. At most MB_CUR_MAX bytes are stored. If wc is a null wide character, a null byte is
stored, preceded by any shift sequence needed to restore the initial shift state; the resulting state
described is the initial conversion state.
6 If wc does not correspond to a valid multibyte character, an encoding error occurs: the wcrtomb_s
function stores the value (size_t)(-1) into *retval and the conversion state is unspecified.
Otherwise, the wcrtomb_s function stores into *retval the number of bytes (including any shift
sequences) stored in the array pointed to by s.
Returns
7 The wcrtomb_s function returns zero if no runtime-constraint violation and no encoding error
occurred. Otherwise, a nonzero value is returned.
K.<IP_ADDRESS> [Restartable multibyte/wide string conversion functions]
1 Unlike mbsrtowcs and wcsrtombs, mbsrtowcs_s and wcsrtombs_s do not permit the ps parameter
(the pointer to the conversion state) to be a null pointer.
K.<IP_ADDRESS>.1 [The mbsrtowcs_s function]
1 Synopsis
#include <wchar.h>
errno_t mbsrtowcs_s(size_t * restrict retval, wchar_t * restrict dst,
rsize_t dstmax, const char ** restrict src, rsize_t len,
mbstate_t * restrict ps);
Runtime-constraints
2 None of retval, src, *src , or ps shall be null pointers. If dst is not a null pointer, then neither
len nor dstmax shall be greater than RSIZE_MAX/sizeof(wchar_t). If dst is a null pointer, then
dstmax shall equal zero. If dst is not a null pointer, then dstmax shall not equal zero. If dst is not a
null pointer and len is not less than dstmax, then a null character shall occur within the first dstmax
multibyte characters of the array pointed to by *src .
3 If there is a runtime-constraint violation, then mbsrtowcs_s does the following. If retval is not
a null pointer, then mbsrtowcs_s sets *retval to (size_t)(-1) . If dst is not a null pointer and
dstmax is greater than zero and not greater than RSIZE_MAX/sizeof(wchar_t), then mbsrtowcs_s
sets dst[0] to the null wide character.
Description
4 The mbsrtowcs_s function converts a sequence of multibyte characters that begins in the conversion
state described by the object pointed to by ps, from the array indirectly pointed to by src into a
sequence of corresponding wide characters. If dst is not a null pointer, the converted characters are
stored into the array pointed to by dst. Conversion continues up to and including a terminating null
character, which is also stored. Conversion stops earlier in two cases: when a sequence of bytes is
encountered that does not form a valid multibyte character, or (if dst is not a null pointer) when len
wide characters have been stored into the array pointed to by dst.[540] If dst is not a null pointer
and no null wide character was stored into the array pointed to by dst, then dst[len] is set to the
null wide character. Each conversion takes place as if by a call to the mbrtowc function.
Footnote 540) Thus, the value of len is ignored if dst is a null pointer.
5 If dst is not a null pointer, the pointer object pointed to by src is assigned either a null pointer (if
conversion stopped due to reaching a terminating null character) or the address just past the last
multibyte character converted (if any). If conversion stopped due to reaching a terminating null
character and if dst is not a null pointer, the resulting state described is the initial conversion state.
6 Regardless of whether dst is or is not a null pointer, if the input conversion encounters a sequence
of bytes that do not form a valid multibyte character, an encoding error occurs: the mbsrtowcs_s
function stores the value (size_t)(-1) into *retval and the conversion state is unspecified.
Otherwise, the mbsrtowcs_s function stores into *retval the number of multibyte characters
successfully converted, not including the terminating null character (if any).
7 All elements following the terminating null wide character (if any) written by mbsrtowcs_s in the
array of dstmax wide characters pointed to by dst take unspecified values when mbsrtowcs_s
returns.[541]
Footnote 541) This allows an implementation to attempt converting the multibyte string before discovering a terminating null character
did not occur where required.
8 If copying takes place between objects that overlap, the objects take on unspecified values.
Returns
9 The mbsrtowcs_s function returns zero if no runtime-constraint violation and no encoding error
occurred. Otherwise, a nonzero value is returned.
K.<IP_ADDRESS>.2 [The wcsrtombs_s function]
1 Synopsis
#include <wchar.h>
errno_t wcsrtombs_s(size_t * restrict retval, char * restrict dst,
rsize_t dstmax, const wchar_t ** restrict src, rsize_t len,
mbstate_t * restrict ps);
Runtime-constraints
2 None of retval, src, *src , or ps shall be null pointers. If dst is not a null pointer, then neither len
shall be greater than RSIZE_MAX/sizeof(wchar_t) nor dstmax shall be greater than RSIZE_MAX. If
dst is a null pointer, then dstmax shall equal zero. If dst is not a null pointer, then dstmax shall not
equal zero. If dst is not a null pointer and len is not less than dstmax, then the conversion shall
have been stopped (see below) because a terminating null wide character was reached or because an
encoding error occurred.
3 If there is a runtime-constraint violation, then wcsrtombs_s does the following. If retval is not
a null pointer, then wcsrtombs_s sets *retval to (size_t)(-1) . If dst is not a null pointer and
dstmax is greater than zero and not greater than RSIZE_MAX, then wcsrtombs_s sets dst[0] to the
null character.
Description
4 The wcsrtombs_s function converts a sequence of wide characters from the array indirectly pointed
to by src into a sequence of corresponding multibyte characters that begins in the conversion state
described by the object pointed to by ps. If dst is not a null pointer, the converted characters are then
stored into the array pointed to by dst. Conversion continues up to and including a terminating
null wide character, which is also stored. Conversion stops earlier in two cases:
— when a wide character is reached that does not correspond to a valid multibyte character;
— (if dst is not a null pointer) when the next multibyte character would exceed the limit of n
total bytes to be stored into the array pointed to by dst. If the wide character being converted
is the null wide character, then n is the lesser of len or dstmax. Otherwise, n is the lesser of
len or dstmax-1.
If the conversion stops without converting a null wide character and dst is not a null pointer, then
a null character is stored into the array pointed to by dst immediately following any multibyte
characters already stored. Each conversion takes place as if by a call to the wcrtomb function.[542]
Footnote 542) If conversion stops because a terminating null wide character has been reached, the bytes stored include those necessary
to reach the initial shift state immediately before the null byte. However, if the conversion stops before a terminating null
wide character has been reached, the result will be null terminated, but might not end in the initial shift state.
5 If dst is not a null pointer, the pointer object pointed to by src is assigned either a null pointer (if
conversion stopped due to reaching a terminating null wide character) or the address just past the
last wide character converted (if any). If conversion stopped due to reaching a terminating null wide
character, the resulting state described is the initial conversion state.
6 Regardless of whether dst is or is not a null pointer, if the input conversion encounters a wide
character that does not correspond to a valid multibyte character, an encoding error occurs: the
wcsrtombs_s function stores the value (size_t)(-1) into *retval and the conversion state is
unspecified. Otherwise, the wcsrtombs_s function stores into *retval the number of bytes in the
resulting multibyte character sequence, not including the terminating null character (if any).
7 All elements following the terminating null character (if any) written by wcsrtombs_s in the array
of dstmax elements pointed to by dst take unspecified values when wcsrtombs_s returns.[543]
Footnote 543) When len is not less than dstmax, the implementation might fill the array before discovering a runtime-constraint
violation.
8 If copying takes place between objects that overlap, the objects take on unspecified values.
Returns
9 The wcsrtombs_s function returns zero if no runtime-constraint violation and no encoding error
occurred. Otherwise, a nonzero value is returned.
L. [Annex L (normative) Analyzability]
L.1 [Scope]
1 This annex specifies optional behavior that can aid in the analyzability of C programs.
2 An implementation that defines __STDC_ANALYZABLE__ shall conform to the specifications in this
annex.[544]
Footnote 544) Implementations that do not define __STDC_ANALYZABLE__ are not required to conform to these specifications.
L.2 [Definitions]
L.2.1 [Definitions]
1 out-of-bounds store
an (attempted) access (3.1) that, at run time, for a given computational state, would modify (or, for
an object declared volatile, fetch) one or more bytes that lie outside the bounds permitted by this
document.
L.2.2 [Definitions]
1 bounded undefined behavior
undefined behavior (3.4.3) that does not perform an out-of-bounds store.
2 Note 1 to entry: The behavior might perform a trap.
3 Note 2 to entry: Any values produced might be unspecified values, and the representation of objects that are written to
might become indeterminate.
L.2.3 [Definitions]
1 critical undefined behavior
undefined behavior that is not bounded undefined behavior.
2 Note 1 to entry: The behavior might perform an out-of-bounds store or perform a trap.
L.3 [Requirements]
1 If the program performs a trap (3.19.5), the implementation is permitted to invoke a runtime-
constraint handler. Any such semantics are implementation-defined.
2 All undefined behavior shall be limited to bounded undefined behavior, except for the following
which are permitted to result in critical undefined behavior:
— An object is referred to outside of its lifetime (6.2.4).
— A store is performed to an object that has two incompatible declarations (6.2.7),
— A pointer is used to call a function whose type is not compatible with the referenced type
(6.2.7, <IP_ADDRESS>, <IP_ADDRESS>).
— An lvalue does not designate an object when evaluated (<IP_ADDRESS>).
— The program attempts to modify a string literal (6.4.5).
— The operand of the unary * operator has an invalid value (<IP_ADDRESS>).
— Addition or subtraction of a pointer into, or just beyond, an array object and an integer type
produces a result that points just beyond the array object and is used as the operand of a unary
* operator that is evaluated (6.5.6).
— An attempt is made to modify an object defined with a const-qualified type through use of an
lvalue with non-const-qualified type (6.7.3).
— An argument to a function or macro defined in the standard library has an invalid value or a
type not expected by a function with variable number of arguments (7.1.4).
— The longjmp function is called with a jmp_buf argument where the most recent invocation
of the setjmp macro in the same invocation of the program with the corresponding jmp_buf
argument is nonexistent, or the invocation was from another thread of execution, or the
function containing the invocation has terminated execution in the interim, or the invocation
was within the scope of an identifier with variably modified type and execution has left that
scope in the interim (<IP_ADDRESS>).
— The value of a pointer that refers to space deallocated by a call to the free or realloc function is
used (7.24.3).
— A string or wide string utility function accesses an array beyond the end of an object (7.26.1,
and 7.31.4).
M. [Annex M (informative) Change History]
M.1 [Fifth Edition]
1 Major changes in this fifth edition (__STDC_VERSION__ 202311L) include:
— allowed for implementations to provide keywords such as bool, static_assert, true, false,
and others with additional support to define them as macros and enable transition of programs
easily;
— removed obsolete sign representations and integer width constraints (so-called "2’s comple-
ment");
— added a one-argument version of static_assert;
— removed support for function definitions with identifier lists;
— mandated function declarations whose parameter list is empty by the same as parameter list
which only contain a single void;
— harmonization with ISO/IEC 9945 (POSIX):
• extended month name formats for strftime
• integration of functions: gmtime_r, localtime_r, memccpy, strdup, strndup
— harmonization with floating point standard IEC 60559:
• integration of binary floating-point technical specification TS 18661-1
• integration of decimal floating-point technical specification TS 18661-2
• integration of decimal floating-point technical specification TS 18661-4a
— made the DECIMAL_DIG macro obsolescent;
— added version test macros to certain library headers to aid in upgrading and portability to be
used alongside the __STDC_VERSION__ macro;
— added the attributes feature, which includes the attributes:
• deprecated, for marking entites as discouraged for future use;
• fallthrough, for explicitly marking cases where fallthrough in switches or labels is
intended rather than accidental;
• maybe_unused, for marking entities which may end up not being used;
• nodiscard, for marking entities which, when used, should have their value handled in
some way by a program;
• reproducible, for marking function types for which inputs may always produce pre-
dictable output if given the same input (e.g., cached data) but for which the order of such
calls still matter;
• unsequenced, for marking function types which always produce predictable output and
have no dependencies upon other data (and other relevant caveats), and,
• _Noreturn , for indicating a function shall never return;
— added the u8 character prefix to match the u8 string prefix;
— mandated all u8, u, and U strings be UTF-8, UTF-16, and UTF-32, respectively, as defined by
ISO/IEC 10646;
— separated the literal, wide literal, and UTF-8 literal, UTF-16 literal, and UTF-32 literal encodings
for strings and characters and now have a solely execution-based version of these, particularly
execution and wide execution encodings;
— added mbrtoc8 and c8rtomb functions missing from <uchar.h>;
— compound literals may also include storage-class specifiers as part of the type to change the
lifetime of the compound literal (and possibly turn it into a constant expression)
— added the constexpr specifier for object definitions and improved what is recognized as a
constant expression in conjunction with the constexpr storage-class specifier;
— added the typeof and typeof_unqual operations for computing the type of an expression;
— improved tag compatibility rules, enabling more types to be compatible with other types;
— added the _BitInt the bit-precise integer types;
— improved rules for handling enumerations without underlying types;
— added a new colon-delimited type specifier for enumerations to specify a fixed underlying
type;
— added a new header <stdbit.h> and a suite of bit and byte-handling utilities for portable
access to many implementation’s most efficiency functionality;
— modified existing functions to preserve the const-ness of the type placed into the function;
— added a feature to embed binary data as faithfully as possible with a new preprocessor directive
#embed;
— added a nullptr constant and a nullptr_t type with a well-defined underlying representa-
tion identical to a pointer to void;
— added the __VA_OPT__ specifier and clarified language in the handling of macro invocation
and arguments;
— mandated support for variably-modified types (but not variable-length arrays themselves);
— ellipses on functions may appear without a preceding parameter in the parameter list of
functions and va_start no longer requires such an argument to be passed to it;
— unicode identifiers allowed in syntax;
— memset_explicit function for writing data;
— certain type definitions, bit-precise integer types, and extended integer types may exceed
the normal boundaries of intmax_t and uintmax_t for signed and unsigned integer types,
respectively;
— names of functions, macros, and variables in this document, where clarified, are potentially
reserved rather than reserved to avoid undefined behavior for a large class of identifiers used
by programs existing and to be created;
— mandated support for call_once;
— allowed ptrdiff_t to be an integer type of at least 16, rather than requiring an integer type
with a width of at least 17;
— added the __has_include feature;
— changed the type qualifiers of the _Imaginary_I and _Complex_I macros;
— added $ and $ into the source and execution character set;
— added the auto type specifier for single object definitions using type inference;
— added the #elifdef and #elifndef conditional inclusion preprocessor directives;
— added the #warning directive;
— binary integer literals and appropriate formatting for input/output of binary integer numbers;
— digit seperators with ’ ;
— removed conditional support for mixed wide and narrow string literal concatenation;
— added support for additional time bases in time.h;
— zero-sized reallocations with realloc are undefined behavior;
— added an unreachable feature which invokes undefined behavior if reached during program
execution;
M.2 [Fourth Edition]
1 There were no major changes in the fourth edition (__STDC_VERSION__ 201710L), only technical
corrections and clarifications.
M.3 [Third Edition]
1 Major changes in the third edition (__STDC_VERSION__ 201112L) included:
— conditional (optional) features (including some that were previously mandatory)
— support for multiple threads of execution including an improved memory sequencing model,
atomic objects, and thread storage (<stdatomic.h> and <threads.h>)
— additional floating-point characteristic macros (<float.h>)
— querying and specifying alignment of objects (<stdalign.h>, <stdlib.h>)
— Unicode characters and strings (<uchar.h>) (originally specified in ISO/IEC TR 19769:2004)
— type-generic expressions
— static assertions
— anonymous structures and unions
— no-return functions
— macros to create complex numbers (<complex.h>)
— support for opening files for exclusive access
— removed the gets function (<stdio.h>)
— added the aligned_alloc, at_quick_exit, and quick_exit functions (<stdlib.h>)
— (conditional) support for bounds-checking interfaces (originally specified in ISO/IEC TR 24731–
1:2007)
— (conditional) support for analyzability
M.4 [Second Edition]
1 Major changes in the second edition (__STDC_VERSION__ 199901L) included:
— restricted character set support via digraphs and <iso646.h> (originally specified in
ISO/IEC 9899:1990/Amd 1:1995)
— wide character library support in <wchar.h> and <wctype.h> (originally specified in
ISO/IEC 9899:1990/Amd 1:1995)
— more precise aliasing rules via effective type
— restricted pointers
— variable length arrays
— flexible array members
— static and type qualifiers in parameter array declarators
— complex (and imaginary) support in <complex.h>
— type-generic math macros in <tgmath.h>
— the long long int type and library functions
— extended integer types
— increased minimum translation limits
— additional floating-point characteristics in <float.h>
— remove implicit int
— reliable integer division
— universal character names (\u and \U)
— extended identifiers
— hexadecimal floating constants and %a and %A printf/scanf conversion specifiers
— compound literals
— designated initializers
— // comments
— specified width integer types and corresponding library functions in <inttypes.h> and
<stdint.h>
— remove implicit function declaration
— preprocessor arithmetic done in intmax_t/uintmax_t
— mixed declarations and statements
— new block scopes for selection and iteration statements
— integer constant type rules
— integer promotion rules
— macros with a variable number of arguments (__VA_ARGS__ )
— the vscanf family of functions in <stdio.h> and <wchar.h>
— additional math library functions in <math.h>
— treatment of error conditions by math library functions (math_errhandling)
— floating-point environment access in <fenv.h>
— IEC 60559 (also known as IEC 559 or IEEE arithmetic) support
— trailing comma allowed in enum declaration
— %lf conversion specifier allowed in printf
— inline functions
— the snprintf family of functions in <stdio.h>
— boolean type in <stdbool.h>
— idempotent type qualifiers
— empty macro arguments
— new structure type compatibility rules (tag compatibility)
— additional predefined macro names
— _Pragma preprocessing operator
— standard pragmas
— __func__ predefined identifier
— va_copy macro
— additional strftime conversion specifiers
— LIA compatibility annex
— deprecate ungetc at the beginning of a binary file
— remove deprecation of aliased array parameters
— conversion of array to pointer not limited to lvalues
— relaxed constraints on aggregate and union initialization
— relaxed restrictions on portable header names
— return without expression not permitted in function that returns a value (and vice versa)
M.5 [First Edition, Amendment 1]
1 Major changes in the amendment to the first edition (__STDC_VERSION__ 199409L) included:
— addition of the predefined __STDC_VERSION__ macro
— restricted character set support via digraphs and <iso646.h>
— wide character library support in <wchar.h> and <wctype.h>


Flow bean name: #{flow1Bean.name}
Has a flow: #{null != facesContext.application.flowHandler.currentFlow}.
address:


Select a corpus from the drop down menu in the top left corner with the label “Corpus”.
Select one of the options from the drop down menu with the label “Search for”.
The search type “words” requires a word to be entered into the text box that is labeled “word”. This search type searches the selected corpus for igts that contain the entered word.
The search type morphemic glosses requires a gloss to be entered into the text box that is labeled “gloss” and/or a morpheme to be to be entered into the text box that is labeled “morpheme”. This search type searches the selected corpus for the igts that contain the entered gloss and/or entered morpheme. If both a morpheme and a gloss are entered, the morpheme and gloss must be aligned in the igt.
The search type morphemes requires a word to be entered into the text box that is labeled “word” and/or a morpheme to be to be entered into the text box that is labeled “morpheme”. This search type searches the selected corpus for the igts that contain the entered word and/or entered morpheme. If both a word and morpheme are entered, the word and morpheme must be aligned in the igt.
The search type pos requires a word to be entered into the text box that is labeled “word” and/or a part of speech to be to be entered into the text box that is labeled “pos”. This search type searches the selected corpus for the igts that contain the entered word and/or entered part of speech. If both a word and a part of speech are entered, the word and part of speech must be aligned in the igt.
The search type “phrases” requires a phrase to be entered into the text box that is labeled “phrase”. This search type searches the selected corpus for igts that contain the entered phrase.
The search type lexical glosses requires a gloss to be entered into the text box that is labeled “gloss” and/or a word to be to be entered into the text box that is labeled “word”. This search type searches the selected corpus for the igts that contain the entered gloss and/or entered word. If both a gloss and word are entered, the word and gloss must be aligned in the igt.
The search type languages requires a language name to be selected from the the drop down menu labeled “language”. This search type searches the selected corpus for igts that contain the selected language name.
Press the green button with the text “Add query”. Pressing this button will add a new query row.
Press the red button with the text “Remove queries”.


A Colorado State University graduate with a degree in biochemistry, Dr. Dougherty went on to attend Boston University School of Dental Medicine. Desiring more expertise in general dentistry, Dr. Dougherty returned to Colorado and completed a rigorous General Practice Residency at Denver Health Medical Center.
Dr. Dougherty is a Colorado native and she and her family live right here in Stapleton. Her husband, Sean, is a sofware engineer. They have three boys, Jack, Cael and Liam.
With a gentle approach and a sincere desire to assist our patients in reaching a state of overall health, Dr. Dougherty and her staff offer you and your family the best treatment and experience possible.
The best way to avoid the expense and hassle of dental problems is with regular check-ups and professional cleanings.
A beautiful, bright, healthy smile is one of the most cost-effective ways to improve your appearance and self-confidence.
95% of patients experience tooth decay at some point in their lives. We have several options for repairing decayed teeth.


Documentation¶
A module for iterating though results from the FEC API.
This module provides several useful utilities for iterating through paginated
results from the FEC API. The meat of
this module is in the filing_iterator.FilingIterator
class, which
encapsulates the logic of interacting with the FEC API and iterating through
the returned results. In theory the FilingIterator
class can iterate
through the results of any endpoint that the FEC API provides.
Included are several iterator factory functions that allow you to create
instances of the FilingIterator
class to handle common endpoints, such as
those for Schedule A filings. In many cases one of the factory functions will
allow you easy access to the data you need, but if you want access to
a specific endpoint of the API you can always create your own iterator
directly.
Note
All of the factory functions and the FilingIterator
class can be
imported directly from the top-level of the module, so the following will
both work:
>>> from fec_filing_iterator import schedules
>>> from fec_filing_iterator.factories import candidates
Iterator Factories¶
-
fec_filing_iterator.factories.
candidates
(**kwargs)¶ Iterator factory that creates an iterator to loop through candidates returned from the FEC /canidates/ endpoint. This endpoint allows you to “fetch basic information about candidates, and use parameters to filter results to the candidates you’re looking for”.
- Kwargs:
All keyword arguments are forwarded to the
filing_iterator.FilingIterator
object
For example, you could get each candidate’s FEC candidate ID with:
>>> for cand in candidates(**kwargs): ... print(cand['candidate_id'])
-
fec_filing_iterator.factories.
committees
(**kwargs)¶ Iterator factory that creates an iterator to loop through committees returned from the FEC /committees/ endpoint. This endpoint allows you to “fetch basic information about committees and filers” and “use parameters to filter for particular characteristics”.
- Kwargs:
All keyword arguments are forwarded to the
filing_iterator.FilingIterator
object
For example, you could get each committee’s FEC ID with:
>>> for cmte in committees(**kwargs): ... print(cmte['committee_id'])
-
fec_filing_iterator.factories.
dates
(date_type, **kwargs)¶ Iterator factory that creates an iterator to loop through different kinds of dates returned from the FEC API. The API has separate endpoints for calendar dates (/calendar-dates/), election dates (/election-dates/), and reporting dates (/reporting-dates/), and this interator factory supports all three. These endpoints give you access to reporting deadlines, election dates, FEC meetings and events, and more.
- Args:
date_type (str): The type of dates to query (‘calendar’, ‘election’, or ‘reporting’)
- Kwargs:
All keyword arguments are forwarded to the
filing_iterator.FilingIterator
object
For example, you could get each election date with:
>>> for elec in dates('election', **kwargs): ... print(elec['election_date'])
-
fec_filing_iterator.factories.
filings
(**kwargs)¶ Iterator factory that creates an iterator to loop through all filings returned from the FEC /filings/ endpoint. This endpoint gives you access to “all official records and reports filed by or delivered to the FEC”.
For example, you could get each filing’s form type with the following (though you’ll be waiting for a very long time):
>>> for filing in filings(**kwargs): ... print(filing['form_type'])
-
fec_filing_iterator.factories.
schedules
(schedule_type, **kwargs)¶ Iterator factory that creates an iterator to loop through all schedules returned from the various FEC schedules endpoints, including /schedules/schedule_a/ and /schedules/schedule_b/. The API has endpoints for schedule types A through F, and this factory supports all of them.
For example, you could get all of the disbursements made by the committee Bernie 2020 with:
>>> bernie_disbursements = [] >>> for filing in schedules('b', **kwargs): ... bernie_disbursements.append(filing)
Filing Iterator¶
-
class
fec_filing_iterator.filing_iterator.
FilingIterator
(*args, api_key=None, params=None, pagination=None, per_page=100, paged=False)¶ Main filing iterator class
This class encapsulates the logic of interacting with the FEC API and iterating through the paged results that are returned in order to present the full set of results as a single, lazily evaluated, iterable stream.
- Args:
Positional arguments are combined to create a URL
- Kwargs:
api_key
(str): FEC API keyparams
(dict): Parameters to pass to the FEC APIpagination
(dict): API pagination information to start your iteration fromper_page
(int): Number of results to return per page, max is 100, which is also the defaultpaged
(bool): Whether the results are paginated using normal page-based pagination or with numbered indexes. Most endpoints are normally paginated, but notably some of the schedule endpoints use indexes
Example:
>>> api_key = 'YOU_FEC_API_KEY' >>> params = { ... 'two_year_transaction_period': [2018, 2020], ... 'committee_id': 'C00696948', ... } >>> for schedule in FilingIterator( ... 'schedules', ... 'schedule_a', ... api_key=api_key, ... params=params ... ): ... print(schedule)
Errors¶
-
exception
fec_filing_iterator.errors.
Error
¶ Base error class for other more specific error classes
-
exception
fec_filing_iterator.errors.
FecApiError
¶ Raised when there is a problem encountered with the FEC API (e.g., when an invalid request is made or when the API rate limit is exceeded after all retries are exhausted)


The weighted spread looks more stationary. However, the fluctuation half-life is very long accrossing zero. We aim to trade as much as we can to maximize the profit of this strategy. Kalman Filter then comes into the play. It could modify the expectation of the next step based on smoothening the prediction and actual probability distribution of return.
Image Source: Understanding Kalman Filters, Part 3: An Optimal State Estimator. Melda Ulusoy (2017). MathWorks. Retreived from: https://www.mathworks.com/videos/understanding-kalman-filters-part-3-optimal-state-estimator--1490710645421.html
KalmanFilter
.In this example, we use the first 20 data points to optimize its initial state. We assume the market has no regime change so that the transitional matrix and observation matrix is [1].
kalmanFilter = KalmanFilter(transition_matrices = [1], observation_matrices = [1], initial_state_mean = new_spread.iloc[:20].mean(), observation_covariance = new_spread.iloc[:20].var(), em_vars=['transition_covariance', 'initial_state_covariance']) kalmanFilter = kalmanFilter.em(new_spread.iloc[:20], n_iter=5) (filtered_state_means, filtered_state_covariances) = kalmanFilter.filter(new_spread.iloc[:20])
currentMean = filtered_state_means[-1, :] currentCov = filtered_state_covariances[-1, :]
KalmanFilter
's results.mean_series = np.array([None]*(new_spread.shape[0]-100))
for i in range(100, new_spread.shape[0]): (currentMean, currentCov) = kalmanFilter.filter_update(filtered_state_mean = currentMean, filtered_state_covariance = currentCov, observation = new_spread.iloc[i]) mean_series[i-100] = float(currentMean)
normalized_spread = (new_spread.iloc[100:] - mean_series)
plt.figure(figsize=(15, 10)) plt.plot(normalized_spread, label="Processed spread") plt.title("Normalized spread series") plt.ylabel("Spread - Expectation") plt.legend() plt.show()


Chapter 2 Statistical Computing with R
R is a complex, powerful statistical programming language. It’s also free! I use R to do all my empirical and methodological work.
R works by scripts. The user writes a program called a “script”" and R executes the program. This might intimidate you a little. That’s okay. It’s easier than it sounds, and I’m here to help you.
We’ll learn a lot about R this semester, but we’ll learn only some aspects of R. I have to include some features of R and exclude others. Just because I show you one way to tackle a problem doesn’t mean it’s the only (or the best) way. But in order to get you working with data ASAP, we have to exclude some important concepts and tools in R.
 RStudio is simply a way to organize our R code. I use RStudio for all my R programming. I even use RStudio to write documents and make presentations using RMarkdown.
2.1 R as a Calculator
To get started with R, just open up RStudio and look around. If you want, you can use R like a calculator–just type directly into the console as you would a calculator.
## [1] 4
## [1] 6
## [1] 8
## [1] 0.6666667
## [1] 20.08554
## [1] 0.6931472
## [1] 1.414214
Review Exercises
Using R as a calculator, calculate the following (in the console):
- \(32 + 17\)
- \(32 \times 17\)
- \(\frac{32}{17}\)
- \(32^2\)
- \(\sqrt{32}\)
- \(\log{32}\)
2.2 Scripts
Ultimately, we’ll want to write all of our code in scripts so that we can modify, reproduce, and check our work. From now on, almost everything we do will go in a script. The idea is not to do an analysis, but to write a script that can do an analysis for us.
To open a new R script, click File, New File, R Script. You can type lines of code directly into this script. In the upper-right corner of the script window, you’ll see a Run button. This runs the entire line that the cursor is currently on or all the highlighted lines. This is equivalent to Command + Enter (or Control + Enter on Windows). Unless the script takes a long time to run (and I don’t think any of ours will), I recommend hitting Command + A (or Control + A on Windows) to highlight the entire script and then Command + Enter (Control + Enter on Windows) to run the entire script. You need to get into the habit of running the entire script, because you want to entire script to work in one piece when you are done. It is much easier to do this if you’re running the entire script all along.
ProTip: To run your code, press command + a (or control + a on Windows) and then press command + enter (or control + enter on Windows).
To save this script, simply click File > Save. I discuss where to save files a little later, but for now, just realize that R scripts will have a .R
extension, such as my-script.R
or important-analysis.R
.
2.2.1 Importance
Doing your work in a script is important. You might have done a statistical analysis before or at least manipulated data with Excel. Most likely, you went though several steps and perhaps ended with a graph. That’s fantastic, but there are several problems.
- If you want to re-do your analysis, you must go through the whole process again.
- You might forget what you did. (I shouldn’t say “might”–you will forget.)
- You cannot easily show others what you did. Instead, they must take your word for it.
- You cannot make small changes to your analysis without going through the whole process again.
Scripting solves each of these problems.
- If you want to re-do your analysis, just open your script and click Run.
- If you forget what you did, just look at your script.
- If you want to show others exactly what you did, just show them your script.
- If you want to make a small change to your analysis, just make a small change to your script and click Run.
Scripting might seem like a lot more work. At first, it will be more work. By the end of the semester, it will be less work. As part of the papers you’ll write for this class, you’ll write a script.
2.3 Object-Oriented Programming
But R is much more powerful than a simple calculator, partly because it allows object-oriented programming. You can store things as “objects” to reference later. Just about anything can be stored as an object, including variables, data sets, functions, numbers, and many others.
2.3.1 Scalars
Let’s start with a single number, sometimes called a “scalar.” Let’s create an object b
that holds or contains the number 2. To do this, we simply use the assignment operator <-
, which we read as “gets.”
We can be very creative with naming objects. Rather than b
, we could have used myobject
, myObject
, my.object
, or my_object
. From a style perspective, I prefer my_object
or important_variable
. In general, you want to give objects descriptive names so that you code is easy to read, but short names so that the code is compact and easy to read and write.
ProTip: Give objects short, descriptive names.
We can now repeat some of the calculations from above, using b
instead of two. Given that you know b
equals two, check that the following calculations make sense.
## [1] 5
## [1] 6
## [1] 8
## [1] 9
## [1] 0.6666667
## [1] 7.389056
## [1] 0.6931472
## [1] 1.414214
You probably realize that it would be easier to just use 2
rather than b
. But we’ll be doing more complicated calculations. Rather than b
holding scalars, it might hold thousands of survey responses. Rather than applying a simple function, we might apply many functions.
2.3.2 Functions
So what is a function? In the above examples exp()
, log()
, and sqrt()
are functions. Importantly, functions are followed immediately by parentheses (i.e., ()
, not []
or {}
, which have different meanings). Arguments are supplied in the functions that tell the function what to do.
You probably didn’t think about it at the time, but you can use many different bases when taking a logarithm. What base did we use when we ran log(b)
? To see this, let’s open the help file.
The section “Usage” shows the typical function syntax. The log()
function takes up to two arguments. The first argument x
is a “numeric vector.” We’ll talk more specifically about numeric vectors below, but for now, we can consider a scalar as a numeric vector. If we provide the arguments in the same order that the appear in the functions in the “Usage” section, then we do not have to name the argument, but we still can. For example, log(b)
and log(x = b)
are equivalent.
ProTip: If you need to know how to use a particular function such as
exp()
, then typehelp(exp)
or?exp
into the console.
You’ll also see from the help file that the default that default is base = exp(1)
, where exp(1)
is just the number \(e\), the base of the natural log. This means that if you don’t specify base
, it will use base = exp(1)
.
## [1] 0.6931472
## [1] 0.6931472
## [1] 0.30103
## [1] 0.30103
Notice that if we put the arguments in the proper order, we do not have to name the argument, so that log(b, base = 10)
is equivalent to log(b, 10)
. However, the meaning of log(b, base = 10)
is more clear, so I prefer that approach.
ProTip: If arguments are supplied to functions in the correct order, then names are unnecessary. However, names should be included whenever there might be doubt about the meaning of the argument. In practice, this most often means leaving the first argument unnamed and naming the rest.
Review Exercises
- Open a new script and give the object
x
the scalar 32. - Repeat the first set of review exercises using
x
rather than the number 32. - Add comments explaining what the code is doing.
2.3.3 Vectors
But if we can only work with single numbers, we won’t get very far.
When we do statistical computing, we’ll usually want to work with collections of numbers (or collections of character strings, like "Republican"
or "Male"
). In an actual problem, the collection might contain thousands or millions of numbers. Maybe these are survey respondents’ ages or hourly stock prices over the last few years. Maybe they are a respondent’s sex (i.e., "Male"
or "Female"
) or party identification (i.e., "Republican"
, "Democrat"
, "Independent"
, or "Other"
).
We’ll call this collection of numbers or character strings a “vector” and we’ll refer to the number of elements in the vectors as the “length” of the vector.
There are several types of vectors, classified by the sort of elements they contain.
numeric
: contain numbers, such as 1.1, 2.4, and 3.4. Sometimes numeric variables are subdivided intointeger
(whole numbers, e.g., 1, 2, 3, etc.) anddouble
(fractions, e.g., 1.47, 3.35462, etc.).character
: contain character strings, such as"Republican"
or"Argentina (2001)"
.factor
: contain character strings, such as"Very Liberal"
,"Weak Republican"
, or"Female"
. Similar tocharacter
, except the entire set of possible levels (and their ordering) is defined.logical
: containTRUE
and/orFALSE
.
<IP_ADDRESS> Numeric Vectors
Rather than the scalar 2
, for example, we might want to work with the collection 2
, 5
, 9
, 7
, and 3
. Let’s assign the collection above to the object a
.
We can create a vector using the “collect” function c()
.
ProTip: To create a vector, one tool we can use is the “collect” function
c()
.
If we want to look at the object a
, we need to enter a
on a line by itself. This will print the object a
for us to inspect. But since we only need to check this once, maybe we just type it in the console instead of including it in the script.
## [1] 2 5 9 7 3
We can now apply functions to the vector a
just like we did for the scalar b
. In each case, the function is applied to each element of the vector.
## [1] 5 8 12 10 6
## [1] 6 15 27 21 9
## [1] 8 125 729 343 27
## [1] 9 243 19683 2187 27
## [1] 0.6666667 1.6666667 3.0000000 2.3333333 1.0000000
## [1] 7.389056 148.413159 8103.083928 1096.633158 20.085537
## [1] 0.6931472 1.6094379 2.1972246 1.9459101 1.0986123
## [1] 0.3010300 0.6989700 0.9542425 0.8450980 0.4771213
## [1] 1.414214 2.236068 3.000000 2.645751 1.732051
## [1] 26
## [1] 5.2
So far, we’ve only used numeric vectors–vectors that contain numbers. But we can create and work with other types of vectors as well. For now, let’s just illustrate two types: vectors of character strings, factors (and ordered factors), and logical vectors.
Review Exercises
- In a script (perhaps the script you began in the exercises above), create a numeric vector assigning the collection 2, 6, 4, 3, 5, and 17 to the object
my_vector
. - Create another numeric vector assigning the collection 64, 13, and 67 to the object
myOtherVector
. - Use the
sum()
function to add the elements ofmy_vector
together. - Use the
sqrt()
function to take the square root of the elements ofmyOtherVector
. - Add 3 to the elements of
my_vector
. - Add comments to the script explaining what this code is doing.
<IP_ADDRESS> Character Vectors
Character strings are simply letters (or numbers, I suppose) surrounded by quotes, such as "Republican"
or "Male"
. If we put c()
(i.e., “combine”) together multiple character strings, then we have a character vector.
## [1] "Republican" "Democrat" "Republican" "Independent"
## Error in x * 3: non-numeric argument to binary operator
A comment about escapes: Inside a string (i.e., text surrounded by quotes, e.g., "Male"
), a backslash \
is considered an “escape.” For example \n
represents new line and \t
represents tab.
## Repub
## lican
## Demo crat
This is important because filenames are sometimes represented with back-slashes, such as data\nominate.csv
. If entered this way, R will not read the data properly, because it treats \n
as an escape and tries to put a new line there.
The solution is to use two back-slashes to represent one (e.g., data\\nominate.csv
). Or you can use a forward-slash /
instead (e.g., data/nominate.csv
). Note that Mac uses forward-slashes in file names by default, so it might not come up. For Windows users, though, you need to use either double back-slashes or switch to forward slashes.
Review Exercises
- Create a character vector containing the elements Male, Female, Male, Male, and Female. Assign this vector to the object
sex
. - Create a character vector containing the elements Liberal, Moderate, Moderate, Conservative, and Liberal. Assign this vector to the object
ideology
.
<IP_ADDRESS> Factor Vectors
A factor vector is much like a character vector, but can only take on predefined values. While we might use a character vector to encode a variable that can have a variety of values (e.g., respondent’s name), we might use a factor to encode a variable that can take on just a few values, such as party identification (e.g., “Republican,” “Independent,” “Democrat,” “Other”). We refer to the possible values of a factor as the “levels.”
Creating a factor is more tricky than creating a numeric or character vector. We might take several approaches, but I suggest the following two-step approach:
- Create a character vector containing the information using
c()
. - Add the levels using the
factor
function.
Factor vectors have two particular advantages over character vectors.
- It allows us to easily see when one category has zero observations.
- It allows us to control the order in which the categories appear. This will be useful, even for categorical variables that have no natural ordering (e.g., race, eye color).
# create a character vector
pid <- c("Republican", "Republican", "Democrat", "Other")
# check type
class(pid)
## [1] "character"
## pid
## Democrat Other Republican
## 1 1 2
We can fix these two problems by using a factor vector instead.
# create a factor vector in two steps
## step 1: create a character vector
pid <- c("Republican", "Republican", "Democrat", "Other")
## step 2: add levels using factor()
pid <- factor(pid, levels = c("Republican",
"Independent",
"Democrat",
"Other"))
# check type
class(pid)
## [1] "factor"
## pid
## Republican Independent Democrat Other
## 2 0 1 1
You can see that by creating a factor variable that contains the level information, we can see that we have no Independents in our sample of four respondents. We can also control the ordering of the categories.
Review Exercises
- Change the character vector
sex
created above to a factor vector. Be sure to explicitly add the levels. The order does not matter. Assign this new factor variable to the objectsex_factor
. - Change the character vector
ideology
created above to a factor vector. Be sure to explicitly add the levels. Use an intuitive ordering. Assign this new factor variable to the objectideology_factor
.
<IP_ADDRESS> Logical Vectors
Logical vectors contain elements that are true or false. R has a special way to represent true and false elements. R uses TRUE
(without quotes) to represent true elements and FALSE
(again, without quotes) to represent false elements. To create a logical vector, we can c()
together a series of TRUE
’s and/or FALSE
’s.
## [1] TRUE TRUE FALSE TRUE FALSE
Review Excercises
- Create the logical vector containing. True, False, False, True, and True. Assign it to the object
logic1
. - Multiply
logic1
times 3. What do you get? Does that make sense?
2.3.4 More Information
You should treat my notes as incomplete.  For a complete description of vectors, see chapter 4 of Advanced R Programming. You can find a similar description in chapter 20 of R4DS.
I don’t mention dates and times at all, but R makes it easy to work with vectors of dates and date-times. We’ll discuss those when we get talk about data wrangling, because it’s a more advanced topic. For reference, you can see the lubridate page on the tidyverse website.
2.4 Missing Values
Missing data are extremely common in statistics. For example, a survey respondent might refuse to reveal her age or income. Or we might not know the GDP or child mortality rate for a particular country in a particular year. In R, we can represent these values with NA
(“not available”). Notice that NA
does not have quotes.
Different functions handle NA
’s differently. Some function will drop missing values (e.g., compute the statistic using the non-missing data) and other functions will fail. Most of the simple functions that we’ll use at first will fail by default (e.g., sum()
, mean()
), but many of the more advanced functions we’ll use later (e.g., lm()
) will drop missing values by default.
x <- c(1, 4, 3, NA, 2)
log(x) # doesn't fail: computes the log for observed data, returns NA for missing data
## [1] 0.0000000 1.3862944 1.0986123 NA 0.6931472
## [1] NA
sum(x, na.rm = TRUE) # doesn't fail: setting na.rm = TRUE tell the function to drop the missing data
## [1] 10
Review Exercises
- Create the object
x
usingx <- c(1, 4, 3, NA, 2)
. Usingmean()
to find the mean ofx
with and without using the argumentna.rm = TRUE
. In a comment, explain why the results are different. Isna.rm = TRUE
a reasonable choice? - Repeat using
sum()
rather thanmean()
.
2.5 Logical Operators
Occasionally, we’d like R to test whether a certain condition holds. We’ll use this most often to choose a subset of a data set. For example, we might need only the data from the 100th Congress (from a data set that contains all Congresses) or only data before 1990 (for a data set that contains all years from 1945 to 2000).
The logical operators in R are <
, <=
, ==
, >=
, >
, and !=
. Notice that we must use ==
, not =
, to test for (exact) equality. We use !=
to test for inequality. We can use &
to represent “and” conditions and |
to represent “or.” Logical operators return either TRUE
or FALSE
.
| Operator | Syntax |
|---|---|
| “less than” | < |
| “less than or equal to” | <= |
| “exactly equal to” | == |
| “greater than or equal to” | >= |
| “greater than” | > |
| “not equal to” | != |
| “or” | | |
| “and” | & |
Try running some of the following. Make sure you can anticipate the result.
# less than
2 < 1
2 < 2
2 < 3
# less than or equal to
2 <= 1
2 <= 2
2 <= 3
# equal to
2 == 1
2 == 2
2 == 3
# greater than or equal to
2 >= 1
2 >= 2
2 >= 3
# greater than
2 > 1
2 > 2
2 > 3
# not equal to
2 != 1
2 != 2
2 != 3
# or
(1 > 2) | (3 > 4)
(1 < 2) | (2 > 4)
(1 < 2) | (3 < 4)
# and
(1 > 2) & (3 > 4)
(1 < 2) & (2 > 4)
(1 < 2) & (3 < 4)
Review Exercises
Use logical operators to test the whether each element of my_vector
(created above) is…
- greater than 3.
- less than 3.
- equal to 3
- greater than 3 or less than 3.
- less than or equal to 3
- greater than or equal to 3
- greater than 2 or less than 1
- greater than 2 and less than 1
- greater than 1 and less than 2
2.6 Packages
Because R is an open-source program, it is easy to write extensions, and thousands of people have. These extensions come in the form of “packages” and these packages contain mostly functions that do stuff with data. For example, I’ve written an R package that does plotting. (I’ve since deferred to ggplot2). I’ve written another package that estimates statistical model. Hadley Wickam has written many R packages, some of which we’ll use. He’s written haven, which we can use to read proprietary data formats, such as Stata (.dta
) files. He’s also written readr, which we can use to quickly read in better formats, such as comma-separated values (.csv
), which I’ll encourage you to use throughout the course. He’s also written a package that is helpful for creating plots called ggplot2. We see that later.
In order to use a package, it must be installed once and then loaded in each session (i.e., after each restart). Some packages come pre-installed in R (e.g., stats, MASS). Some of these pre-installed packages are automatically loaded in each session (e.g., stats), while others must be loaded manually in each session (e.g., MASS) if you want to use them. Other packages that do not come pre-installed with R need to be installed manually (but just once) and loaded in each session.
2.6.1 Installing Packages
If you click the “Packages” tab in RStudio (positioned in the upper-right panel by default), it will show you a list packages that are currently installed. I’ve attached a screenshot of my installed packages below, but your’s might look slightly different–I’ve probably installed a lot more than you.
If you want to use a function from a package and it is not installed, you must first install it. Most R packages are available on CRAN, and can be installed with the install.packages()
function.
install.packages("ggrepel")
install.packages("ggthemes")
If you want to go ahead and install these packages, feel free–we’ll use them later. RStudio might ask you to choose a mirror. If so, just choose something close to you–it doesn’t really matter.
If you look at your list of installed packages again, you should see ggrepel
and ggthemes
.
You only need to install a package once. Once you’ve installed it, you have it on your hard drive.
2.6.2 Loading Packages
In order to use function from a package, though, the package must be installed and loaded. In the packages list, the check box (beside the package name) indicates whether the package is loaded. In the screenshot above, you can see that I only had one package loaded at the time I took the screenshot–blme, a package useful for estimating Bayesian linear mixed-effects models.
Let’s see how to access functions that are in packages. First, let’s create some data to plot.
Now let’s try to use the qplot()
function in the ggplot2 package to create a scatterplot of x
and y
. I’m assuming that you’ve already installed the ggplot2 package (it’s included in the tidyverse package).
Now, let’s try to use qplot()
.
## Error in qplot(x, y): could not find function "qplot"
You’ll notice that the qplot()
function cannot be found. That’s because while ggplot2 is installed (i.e., present in the library), it is not loaded (i.e., off the shelf). If you want to use a function from the ggplot2 package, you need to load the package using the library()
function. You need to load the package each time you start a new session (e.g., restart RStudio), so be sure to include this in your script. Notice that you do not need to use quotes around the name of the package when using the library()
function.
When we use library()
, it loads the entire set of functions in the package into our workspace, making them all accessible to us. There are literally hundreds of functions in the ggplot2 package. If we prefer to avoid loading all the functions, we can use the syntax package::function()
to tell R where to find the function in the library without loading all the functions into the workspace.
ggplot2::qplot(x, y)
will work whether or not ggplot2 is loaded.
I don’t have strong feelings about which approach is better–it depends on the context. If you only need to use one function from package one time, then perhaps it makes more sense to use the package::function()
approach. If you’ll be using many functions many times, then it makes sense to use library()
. Use whichever makes most sense to you. However, I’ll tend to use package::function()
a lot, because it makes it clear where the function is coming from.
Review Exercises
- Install and load the GGally package. Write a simple example of a function in the package. Use example code from the vignette.
- Install and load the ggdag package. Write a simple example of a function in the package. Use example code from the vignette.
- Install and load the texreg package. Write a simple example of a function in the package. Perhaps try the code below. If you are feeling ambitious, you might try compiling a LaTeX document with the LaTeX code output by
texreg()
. If you do this, be sure to start with the LaTeX template from 50-legs or the very minimal template from Homework 1.
library(texreg)
fit1 <- lm(Fertility ~ . , data = swiss)
fit2 <- update(fit1, . ~ . -Examination)
screenreg(list(fit1, fit2))
texreg(list(fit1, fit2))
2.2.2 Comments
You can also insert comments into R scripts. This is very important, especially when you are first learning to program. To insert a comment, simply type a pound or hash sign
#
(i.e., “hashtag” to me) anywhere in the code. Anything on the line after the hash will be ignored. I’ll always carefully comment my R code, and I’ll be even more careful about it for this class. Here’s an example of some commented code for the previous example.Comments in R