简体   繁体   中英

Increment/Decrement operators on functions with return type int

The following code doesn't run. Can I say increment/decrement operators won't work on functions with return type int?

int main()
{
    char x[] = {"test"};
    int size = strlen(x);            //works :)
    int size2 = --strlen(x);         //doesn't work

    return 0;
}

Error is:

error: lvalue required as decrement operand
    9 |         int size2 = --strlen(x);         //doesn't work
      |                     ^~

The prefix decrement operator -- decrements the object which is the subject of the operator. The return value of a function is just that, a value and not an object. It's the same as if you tried to do --4 .

If you want to assign 1 less than the length of x to size2 , you would do it like this:

int size2 = strlen(x) - 1;

As the error message says you need an object (lvalue) to apply the operator.

You could write for example

int size2 = strlen(x); 
--size2;

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