Context-Free Language

1 min read Updated Fri Apr 24 2026 07:36:29 GMT+0000 (Coordinated Universal Time)

A language that can be generated by a CFG.

L(G)={xΣSx}L(G) = \set{ x \in \Sigma^* \mid S \Rightarrow^* x }

A language LL is context-free iff there exists a CFG GG such that it generates LL. All regular languages are context-free.

Properties

If L1L_1 and L2L_2 are CFLs, then the following are also CFLs:

  • Union
    L1L2L_1 \cup L_2
  • Concatenation
    L1L2L_1L_2
  • Kleene star
    L1L_1^*

The following are not necessarily CFLs:

  • Intersection
    L1L2L_1 \cap L_2
  • Complementation
    L1L_1'

Examples

Palindrome

Language of palindromes over Σ={a,b}\Sigma = \set{a, b}. Λ,a,b\Lambda, a, b are palindromes.

If xx is palindrome then axaaxa and bxbbxb are palindromes.

SΛ    a    b    aSa    bSbS \rightarrow Λ\;|\;a\;|\;b\;|\;aSa\;|\;bSb

This language is not regular, but context-free.

a^n b^n

Language of strings with equal number of a’s followed by b’s.

Grammar:

SΛ    aSbS \rightarrow Λ\;|\;aSb

This language is not regular, but context-free.

Syntax of Programming Languages

Programming languages (such as Python, Java) have syntax that can be described by CFGs. Used in compiler design to parse code and check for syntax errors.