CodeBlanks Logo Icon CodeBlanks

setlocale

Learn locale settings with setlocale.

setlocale

setlocale changes the program's locale; it is defined in <locale.h>. The locale affects character classification, number formatting and date formatting.

setlocale(LC_ALL, "C") selects the minimal locale; it only knows the basic ASCII set. The empty string "" reads from environment variables (LANG, LC_ALL). On success it returns the locale name; on failure it returns NULL. In this lesson we use "C" for deterministic output.

Getting the locale name

When setlocale succeeds it returns the locale name as a string. setlocale(LC_ALL, "C") returns "C" on every system, so the output is deterministic.

The environment locale (empty string) depends on the LANG variable and may differ between test machines. The locale also affects the behavior of mbstowcs and isalpha; so you must call setlocale before multibyte conversion.

Practice Set the locale and print it

Set the locale with char *loc = setlocale(LC_ALL, "C");. Print the returned name with printf("yerel: %s\n", loc);. Add the <locale.h> header.

Starter code

main.c
#include <stdio.h>
#include <locale.h>

// Set the locale to 'C' and print the returned name

int main(void) {
    return 0;
}

Sample solution

main.c
#include <stdio.h>
#include <locale.h>

int main(void) {
    char *loc = setlocale(LC_ALL, "C");
    printf("yerel: %s\n", loc);
    return 0;
}

Expected output

yerel: C

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 setlocale call

Question
char *loc = setlocale(____, "C");
Answer
char *loc = setlocale(LC_ALL, "C");

Explanation: LC_ALL sets all categories at once.

2 Match locale categories

Term Meaning
LC_ALL All categories
LC_CTYPE Character class
LC_TIME Date format
LC_NUMERIC Number format

3 What does setlocale(LC_ALL, "C") return?

  • NULL
  • 0
  • The string "C" Correct answer
  • "tr_TR"

Explanation: On success it returns the "C" locale name.

All lessons in Advanced