user2150989
user2150989

Reputation: 233

C/C++: char() used as a function

I recently came across the following code that uses syntax I have never seen before:

std::cout << char('A'+i);

The behavior of the code is obvious enough: it is simply printing a character to stdout whose value is given by the position of 'A' in the ASCII table plus the value of the counter i, which is of type unsigned int.

For example, if i = 5, the line above would print the character 'F'.

I have never seen char used as a function before. My questions are:

  1. Is this functionality specific to C++ or did it already exist in strict C?
  2. Is there a technical name for using the char() keyword as a function?

Upvotes: 0

Views: 94

Answers (2)

tucuxi
tucuxi

Reputation: 17945

That is C++ cast syntax. The following are equivalent:

std::cout << (char)('A' + i); // C-style cast: (T)e
std::cout << char('A' + i);   // C++ function-style cast: T(e); also, static_cast<T>(e)

Stroustroup's The C++ programming language (3rd edition, p. 131) calls the first type C-style cast, and the second type function-style cast. In C++, it is equivalent to the static_cast<T>(e) notation. Function-style casts were not available in C.

Upvotes: 2

toth
toth

Reputation: 2552

This is not a function call, it's instead a typecast. More usually it's written as

std::cout << (char)('A'+i);

That makes it clear it's not a function call, but your version does the same. Note that your version might only be valid in C++, while the one above work in both C and C++. In C++ you can also be more explicit and write

std::cout << static_cast<char>('A'+i);

instead. Not that the cast is necessary because 'A'+i will have type int and be printed as an integer. If you want it to be interpreted as a character code you need the char cast.

Upvotes: 1

Related Questions