Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

compiler warning left-hand comma c

Hello I am new to coding and I wrote this few lines to receive only lowercase but my compiler only gives me this warning:

prog.c:12:15: error: left-hand operand of comma expression has no effect [-Werror=unused-value]
     b = ("%#x", a) + 32;
    #include<stdio.h>

int main()
{
    
    char a;
    int b;
    
    printf("Bitte geben Sie einen Grossbuchstaben ein: ");
    scanf("%c", &a);
    
    b = ("%#x", a) + 32;
    
    
    printf("%c", b);
    
}
question from:https://stackoverflow.com/questions/65943742/compiler-warning-left-hand-comma-c

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As the message suggests, a comma operator is used in the part ("%#x", a).

This means

  1. Evaluate the left-hand operand "%#x" and discard the result
  2. Evaluate the right-hand operand a and make the result of evaluation to its value

In this case "%#x" does nothing, so you should simply remove that.

In other words, the line

    b = ("%#x", a) + 32;

should be

    b = a + 32;

Also here is a better code:

  • Check the result of scanf().
  • Use tolower() to convert a character to lowercase.
#include<stdio.h>
#include<ctypes.h>

int main(void)
{
    
    char a;
    int b;
    
    printf("Bitte geben Sie einen Grossbuchstaben ein: ");
    if (scanf("%c", &a) != 1)
    {
        fputs("read error
", stderr);
        return 1;
    }

    
    b = tolower((unsigned char)a);
    
    
    printf("%c", b);
    
}

The argument of tolower is casted to unsigned char for making sure that the argument is in the range of unsigned char (to avoid giving a negative number in environments where char is signed).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...