0

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?
user2150989
  • 233
  • 1
  • 7

2 Answers2

2

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.

tucuxi
  • 17,561
  • 2
  • 43
  • 74
  • Thanks for the explanation. My next question would then be what is the purpose of having multiple types of casts. It looks like I have some more research to do. Here is a related question/answer I will start my reading with:http://stackoverflow.com/questions/4474933/what-exactly-is-or-was-the-purpose-of-c-function-style-casts – user2150989 Jun 26 '14 at 03:37
  • Mr Stroustroup (creator of C++) did not like the C-style cast -- it is certainly dangerous, as its effects depend heavily on what it is converting; that is, from simple inspection, it is hard to know the exact conversion that will be taking place. So he added several function-style variants, including all the types in [this question](http://stackoverflow.com/questions/332030) – tucuxi Jun 26 '14 at 18:10
1

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.

toth
  • 2,519
  • 1
  • 15
  • 23
  • My copy of K&R's "The C programming language" insists that casts can only be performed via `(type)value`, and does not describe the `type(value)` syntax at all. Therefore, I think it is a C++ extension. – tucuxi Jun 25 '14 at 18:29
  • @tucuxi, you are probably correct, edited to reflect. – toth Jun 25 '14 at 18:33