简体   繁体   中英

question about subtraction of two strings in c programming

I have a question from an interview and need a little help:

What is "abcd" - "xyz"?

  1. Address
  2. Integer
  3. The operation is illegal for the compiler
  4. str
  5. none of the above

I'm pretty sure its 4. can someone tell me if its true and whats the correct explanation. thanks!

Normally in C, the difference between two pointers is an integer of type ptrdiff_t representing the distance between the two objects pointed at. That's the interpretation which would apply here because a string literal is shorthand for an array of characters and, as with any array, using it in an expression causes the array to "decay" into a pointer to its first element.

However, "abcd" - "xyz" is Undefined Behaviour because subtraction of one pointer from another is only defined if the two pointers refer to objects in the same array. (Otherwise, the "distance between the two objects" is meaningless.)

The multiple choice provided doesn't list "Undefined Behaviour" as an option. Option 3 would not be correct unless you know something about the particular compiler referred to: since the standard does not define behaviour, a compiler is free to implement anything it sees fit. It could accept the expression and return a meaningless result, or it could generate an error message and terminate the compilation, or it could do anything else that seemed reasonable to the compiler writer.

So if I were asked this question, I'd go for answer 5 ("None of the above") and be prepared to explain my reasoning.

First of all, let's take a sample program:

#include <stdio.h>

int main(void) {
    char str1[] = "abcd";
    char str2[] = "xyz";

    int x = str1 - str2;

    printf("Subtraction diff: %d\n", x);

    return 0;
}

You thinks that the program does subtracts two strings, right? But, No!

The program doesn't subtracts two strings, we've two char[] here. x holds the memory address difference between str1[] and str2[] for representation. This can be pretty much anything arbitrary. The aforementioned program will display 4 , ie space between the start of the first string and the start of the second one on your stack is 4 bytes.


Related: In C++, you could take the help of auto keyword in this example to let the compiler decide the appropriate type for the expression, similar to:

auto x = str1 - str2;
std::cout << x;

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