Warnings and Assertions

GLib defines several warning functions and assertions which can be used to warn of programmer errors when calling functions, and print error messages from command line programs.

Pre-condition Assertions

The g_return_if_fail(), g_return_val_if_fail(), g_return_if_reached() and g_return_val_if_reached() macros are intended as pre-condition assertions, to be used at the top of a public function to check that the function’s arguments are acceptable. Any failure of such a pre-condition assertion is considered a programming error on the part of the caller of the public API, and the program is considered to be in an undefined state afterwards. They are similar to the libc assert() function, but provide more context on failures.

For example:

g_dtls_connection_shutdown (GDtlsConnection  *conn,
                            gboolean          shutdown_read,
                            gboolean          shutdown_write,
                            GCancellable     *cancellable,
                            GError          **error)
  // local variable declarations

  g_return_val_if_fail (G_IS_DTLS_CONNECTION (conn), FALSE);
  g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), FALSE);
  g_return_val_if_fail (error == NULL || *error == NULL, FALSE);

  // function body

  return return_val;

g_warn_if_fail() and g_warn_if_reached() behave similarly, but they will not abort the program on failure. The program should be considered to be in an undefined state if they fail, however.


g_print() and g_printerr() are intended to be used for output from command line applications, since they output to standard output and standard error by default — whereas functions like g_message() and g_log() may be redirected to special purpose message windows, files, or the system journal.

The default print handlers may be overridden with g_set_print_handler() and g_set_printerr_handler().


If the console encoding is not UTF-8 (as specified by g_get_console_charset()) then these functions convert the message first. Any Unicode characters not defined by that charset are replaced by '?'. On Linux, setlocale() must be called early in main() to load the encoding. This behaviour can be changed by providing custom handlers to g_set_print_handler(), g_set_printerr_handler() and g_log_set_handler().

Debugging Utilities