Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring a variable with two types: "int char"

I'm a C++ beginner, and I'm reading Bjarne Stroustrup's Programming: Principles and Practice Using C++.

In the section on 3.9.2 Unsafe conversions, the author mentioned

When the initializer is an integer literal, the compiler can check the actual value and accept values that do not imply narrowing:

int char b1 {1000};     // error: narrowing (assuming 8-bit chars) 

I'm puzzled by this declaration. It uses two types (int and char). I have never seen such declaration in Java and Swift before (the two languages I'm relatively familiar with). Is this a typo or a valid C++ syntax?

like image 588
Thor Avatar asked Jul 09 '18 06:07

Thor


People also ask

Can a variable have two data types?

How can a variable have 2 data types? It cannot. An object has one type. A single type can represent values of different types (unions, std::variant ).

How do you declare a variable with a double data type?

A variable can be declared as double by adding the double keyword as a prefix to it. You majorly used this data type where the decimal digits are 14 or 15 digits.

How do you declare a variable of char?

If a value is to be assigned at the time of declaration, you can use this syntax: char variable-name = 'value'; The variable-name is the name of the char variable. The value is the value to be assigned to the char variable.

Can we declare char for int?

If we direct assign char variable to int, it will return the ASCII value of a given character. If the char variable contains an int value, we can get the int value by calling Character. getNumericValue(char) method. Alternatively, we can use String.


1 Answers

It's a mistake in the book. That is not a valid C++ declaration, even without the supposed narrowing conversion.

It isn't mentioned in any of the erratas on Bjarne Stroustrup's page(4th printing and earlier), though, which is odd. It's a clear enough mistake. I imagine since it's commented with //error few people notice the mistake in the declaration itself.

like image 123
StoryTeller - Unslander Monica Avatar answered Sep 20 '22 23:09

StoryTeller - Unslander Monica