-4

What is the difference between (int)b and int(b)?

Is it possible that the values will ever be different for int(b) and (int)b? If not, then what is the difference between both?

Can someone please kindly clarify?

My code:

cout << "The expression is " << a + b << endl;
cout << "The expression is " << a + int(b) << endl;
cout << "The expression is " << a + (int)b << endl;
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • 3
    Please read [ask] with a [mcve] not fragments of code. All information should be in the question as formatted text and not images or links. C++ is a context sensitive grammar (language) so code fragments without context are hard to interpret. If you are _"...a beginner at c ..."_ why have you added the C++ tag? – Richard Critten Jan 23 '23 at 13:23
  • 2
    Have a look here https://en.cppreference.com/w/cpp/language/explicit_cast – eike Jan 23 '23 at 13:25
  • 3
    _"I am a beginner at c"_ - C doesn't have the functional style cast `int(b)` afaik. – Ted Lyngmo Jan 23 '23 at 13:29
  • 2
    Your code is clearly C++, not C. – molbdnilo Jan 23 '23 at 13:30
  • [Why should i not upload images of code/data/errors?](https://meta.stackoverflow.com/questions/285551/why-should-i-not-upload-images-of-code-data-errors) – 463035818_is_not_an_ai Jan 23 '23 at 13:42
  • Voted to reopen. "needs details or clarity"? Really? – Pete Becker Jan 23 '23 at 15:16

1 Answers1

5

Both are explicit cast expression.

  • (int) b is a so-called C-style cast expression which will try to cast the value of b to the int type

  • int(b) is a so-called functional-style cast expression. According to cppreference

    If there is exactly one expression in parentheses, this cast expression is exactly equivalent to the corresponding C-style cast expression

So in your context both are strictly equivalent. That being said the idiomatic C++ way as casting would be: static_cast<int>(b). The good news with that last way is that is would not inadvertently ignore a const modifier...

Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252
  • Despite what cppreference says, they're not exactly the same. They're different when the name of the type being converted to has more than one word. Converting to `long long` can be done with a C-style cast, but not with a function-style cast. – Pete Becker Jan 23 '23 at 15:14
  • @PeteBecker that's on cppreference in the sentence directly preceding the one quoted – Cubbi Jan 23 '23 at 21:39
  • @Cubbi — doesn’t matter, since it’s not in this answer. – Pete Becker Jan 23 '23 at 22:11