如何将警告“从'int'转换为'char'可能会改变其值” [英] How to drop the warning "conversion to ‘char’ from ‘int’ may alter its value"

查看:598
本文介绍了如何将警告“从'int'转换为'char'可能会改变其值”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

虽然我 $ 这样的数字(unsigned char)32 还是可以解决的

I though that if I cast a number like this (unsigned char)32 it will be enough to fix the compiler warning, but it wasn't like how I planed.

这里我有程序的以下部分实际解释了问题:

Here i have the following part of the program which actually explain the problem:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main(void){
    char *ptr = malloc(6);
    const char *name = "MICHI";
    unsigned int i = 0;

    if(ptr){
        strcpy(ptr, name);
        ptr[strlen(ptr)] = '\0';
    }else{
        return 1;
    }

    while(ptr[i] != '\0'){
        if((ptr[i] >= 'A') && (ptr[i] <= 'Z')){
            ptr[i] += (unsigned char)32;
        }
        i++;
    }

    printf("Name = %s\n",ptr);
    if(ptr){
        free(ptr);
        ptr = NULL;
    }
}

当我尝试在编译器警告为ON的情况下进行编译时,我明白了:

When I try to compile it with compiler warnings ON, I get this:

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

这意味着以下 ptr [i] + =(无符号字符) 32; 不能解决我的问题。

This means thet the following ptr[i] += (unsigned char)32; doesn't provide a solution to my problem.

我的问题是,如何删除此警告,因为我对此一无所知。

My question is, how to drop this warning because I have no clue about it.

Idone 并没有多大帮助,因为我认为所有警告都已关闭。

Ideone doesn't helps to much, because I think that all warnings are Turned off.

推荐答案

OP使用的警告级别非常挑剔

OP is using a level of warning that is very picky


警告:从'int'转换为'char'可能会改变其值[-Wconversion]

warning: conversion to 'char' from 'int' may alter its value [-Wconversion]



  // Both cause the warning
  ptr[i] += (unsigned char) 32;
  ptr[i] = tolower(ptr[i]);

要解决该警告,请明确

  ptr[i] = (char) (ptr[i] + 32);
  ptr[i] = (char) tolower(ptr[i]);






[详细信息]涉及诸如 char,short,unsigned char,_Bool,... 将使用常规的 integer促销将促销对象提升为 int / unsigned ,例如 ptr [i] 。因此,将 int / unsigned 分配回 char 会触发警告。


[Detail] Operations that involving narrow type like char, short, unsigned char, _Bool, ... will have that operand promoted, using the usual integer promotions to int/unsigned, like ptr[i]. So assigning that int/unsigned back to a char triggers the warning. An explicit cast of the result quiets the warning.

许多编译忽略了 [-Wconversion]或等效的选项,并且因此不会看到警告。

Many compilations omit the [-Wconversion] or equivalent option and so will not see the warning.

这篇关于如何将警告“从'int'转换为'char'可能会改变其值”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆