简体   繁体   中英

I don't understand what args[0][0]-'!' means

I stumbled upon this block of code and I want to understand what args[0][0]-'!' means?

else if (args[0][0]-'!' ==0)
{   int x = args[0][1]- '0'; 
    int z = args[0][2]- '0'; 

    if(x>count) //second letter check
    {
    printf("\nNo Such Command in the history\n");
    strcpy(inputBuffer,"Wrong command");
    } 
    else if (z!=-48) //third letter check
    {
    printf("\nNo Such Command in the history. Enter <=!9 (buffer size        is 10 along with current command)\n");
    strcpy(inputBuffer,"Wrong command");
    }
    else
    {

        if(x==-15)//Checking for '!!',ascii value of '!' is 33.
        {    strcpy(inputBuffer,history[0]);  // this will be your 10 th(last) command
        }
        else if(x==0) //Checking for '!0'
        {    printf("Enter proper command");
            strcpy(inputBuffer,"Wrong command");
        }

        else if(x>=1) //Checking for '!n', n >=1
        {
            strcpy(inputBuffer,history[count-x]);

        }

    }

This code is from this github account: https://github.com/deepakavs/Unix-shell-and-history-feature-C/blob/master/shell2.c

args is a char** , or in other words, an array of strings (character arrays). So:

args[0]             // first string in args
args[0][0]          // first character of first string in args
args[0][0]-'!'      // value of subtracting the character value of ! from
                    // the first character in the first string in args
args[0][0]-'!' == 0 // is said difference equal to zero

In other words, it checks if the first string in args starts with the ! character.

It could (and arguably should) be rewritten as

args[0][0] == '!'

As well as (but don't use this one):

**args == '!'

'!' is just a textual representation of a numerical value which encodes the exclamation mark in a specified encoding. args[0][0] is the first character of the first element of the array.

So when x - y == 0 ? Move y on the other side, when x == y , so that code is equivalent to args[0][0] == '!' .

I don't see any practical reason to express the equivalence as a subtraction in the example though.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM