Electronic structure and formation energies of substitutional carbon impurities in hexagonal GaN and AlN were studied by quantum molecular dynamics. Substitutions on both cation and anion sites were considered. C-cation is a shallow donor, while C-N is a shallow acceptor. A DX-like configuration is metastable for C-Ga and C-Al(0), and stable for C-Al(-). The solubility of carbon is excellent, but it is accompanied by efficient self-compensation of carbon accepters by carbon donors. This is due to two factors: (i) the large energy gain induced by electron transfer from C-cation to C-N, which is close to the band gap energy, and (ii) the large binding energy (similar to 1 eV) of nearest neighbor C-cation(+)-C-N(-) pairs. (C) 1996 American Institute of Physics.