具有自己的getch函数的隐式转换警告 [英] Implicit conversion warning with own getch function

查看:89
本文介绍了具有自己的getch函数的隐式转换警告的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现了conio.h的getch()的c实现.可悲的是它带有一个转换警告编译,我不知道该怎么做才能正确解决它.我找到了链接,但是我没有不知道如何实现.

I found a c implementaion of conio.h's getch(). Sadly it compiles with a comversion warning, and i don't know what i should do to solve it correctly. I found this link, but i don't know how to implement it.

#include<termios.h>
#include<unistd.h>
#include<stdio.h>
#include"getch.h"

/* reads from keypress, doesn't echo */
int getch(void)
{
    struct termios oldattr, newattr;
    int ch;
    tcgetattr( STDIN_FILENO, &oldattr );
    newattr = oldattr;
    newattr.c_lflag &= ~( ICANON | ECHO );
    tcsetattr( STDIN_FILENO, TCSANOW, &newattr );
    ch = getchar();
    tcsetattr( STDIN_FILENO, TCSANOW, &oldattr );
    return ch;
}

/* reads from keypress, echoes */
int getche(void)
{
    struct termios oldattr, newattr;
    int ch;
    tcgetattr( STDIN_FILENO, &oldattr );
    newattr = oldattr;
    newattr.c_lflag &= ~( ICANON );
    tcsetattr( STDIN_FILENO, TCSANOW, &newattr );
    ch = getchar();
    tcsetattr( STDIN_FILENO, TCSANOW, &oldattr );
    return ch;
}

CLANG 3.5返回:

CLANG 3.5 returns:

getch.c:13:24: warning: implicit conversion changes signedness: 'int' to 'unsigned int' [-Wsign-conversion]
    newattr.c_lflag &= ~( ICANON | ECHO );
                    ~~ ^~~~~~~~~~~~~~~~~~
getch.c:27:24: warning: implicit conversion changes signedness: 'int' to 'unsigned int' [-Wsign-conversion]
    newattr.c_lflag &= ~( ICANON );
                    ~~ ^~~~~~~~~~~
2 warnings generated.

推荐答案

由于整数提升,这些定义被提升为int,但c_lflag成员为无符号整数.

Due to integer promotions those defines are promoted to int, but the c_lflag member is an unsigned integer.

确保按无符号类型完成按位运算:

Make sure the bitwise operation is done in an unsigned type:

 newattr.c_lflag &= ~( 0u | ICANON | ECHO );
                        ^   

这篇关于具有自己的getch函数的隐式转换警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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