Jack
Jack

Reputation: 16724

How to remove warning: conversion to ‘char’ from ‘int’ may alter its value?

I have a char buf[3]; array where I need to put: buf[0] = ch where ch is an int. But the compiler give the following warning:

conversion to ‘char’ from ‘int’ may alter its value

How do I remove this? I tried cast to unsigned char but no luck.

Upvotes: 2

Views: 4183

Answers (2)

perilbrain
perilbrain

Reputation: 8197

A char is one byte long while an integer is generally 4 bytes (implementation defined).
If you try to cast an integer to char, obviously you'll loose upper three bytes.

You can do so by buf[0]=(char)ch, if you are sure that your int is not longer than 1 byte. Otherwise there is a loss of information.

Upvotes: 5

Stephen Canon
Stephen Canon

Reputation: 106167

Use an explicit cast:

buf[0] = (char)ch;

Upvotes: 8

Related Questions