0

I encountered a code with the function arithmetic(), basically, for multiplication, the thing that bothered me was the use "!" the NOT unary operator before the function call. code goes like:-

    #include<iostream>
    using namespace std;
    
    int arithmetic(int,int);
    int main()
    {
       return !arithmetic(11,9);
    }
    
    int arithmetic(int a, int b)
    {
        return(printf("%d",(++a*--b)));
    }

p.s:- removing the ! operator brings no change to the result.

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547
  • 1
    It `NOT`s the result of the function call. – tkausl Aug 08 '21 at 07:49
  • Note that `printf` returns the number of chars actually printed. – hessam hedieh Aug 08 '21 at 07:50
  • It nots the return value not what the function does. Check the program return value and I am sure it does change – Lala5th Aug 08 '21 at 07:50
  • You should make the function main() return 0 if there is no error. If there is any error, then the function main would return a non-zero. – Job_September_2020 Aug 08 '21 at 07:51
  • thanks, everyone I understood the purpose of the use of ! operator. – Shubham Saini Aug 08 '21 at 07:59
  • 1
    `printf` returns the number of chars written on success and a negative value, if there's an error. The operator `!` interprets the operand as `bool` and any non-zero operant is converted to `true` which is always the case (either there's an error or at least one char is written) and the result of the negation is `false` which, when converted to bool yields `0`. This code is just confusing and probably incorrect for this reason (we'd expect a non-zero exit code on an error). – fabian Aug 08 '21 at 08:03

2 Answers2

2

return !arithmetic(11,9); applies the ! (not) operator to the result of arithmetic(11,9). That is, it converts the result of arithmetic(11,9) to a boolean value and inverts it. Thus it's true when arithmetic(11,9) returned 0 and false in any other case.

This boolean value will be converted to an integer again, because main returns int. This question covers what the return value of main means.

Now the result of arithmetic(11,9) is the result of printf("%d",(++a*--b)), which is the number of characters printed or a negative value in case an error occurred.


All in all main will return 0 when printf printed any characters or if an error occurred (because !negativeInt == true) and it will return 1 if and only if no characters where printed and also no error occured. So it's not really usefull here.

Lukas-T
  • 11,133
  • 3
  • 20
  • 30
0

When a function returns a value, the ! (i.e Logical negation operator ) negates the value. It is mainly used with the boolean values.

As your function arithmetic is only printing something. The returned value is never used anywhere. Hence, you are not seeing any effect even after removing the ! symbol.

hessam hedieh
  • 780
  • 5
  • 18