Home > Software design >  How to make the conversion from 'int' to 'char' reasonable under -Werror=convers
How to make the conversion from 'int' to 'char' reasonable under -Werror=convers

Time:12-17

error: conversion from ‘int’ to ‘char’ may change value [-Werror=conversion]

build cmd example: g -std=c 11 test.cpp -o a.out -Werror=conversion

    auto index = 3;
    char singleChar = 'A'   index; // I want to get A-Z

I hope sigleChar is dynamically assigned. could you pls help me to solve this error report without using switch? How would it be better to write code?

CodePudding user response:

'A' index; // I want to get A-Z would only works for ASCII, not EBCDIC for example.

A more portable solution (and not int to char conversion involved) is array indexing:

char singleChar = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"[index];

CodePudding user response:

You have to typecast it to a char:

auto index = 3;
char singleChar {static_cast<char>('A'   index)};
  • Related