C++ return statement | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

C++ return statement

Why is the output 6 instead of 4? int f(int a) { return ++a; } int f(unsigned int a) { return --a; } int main() { cout<<f(5); }

22nd Jul 2020, 4:59 AM
Solus
Solus - avatar
3 Answers
+ 1
Integer literals are by default be created as `int` but code parser considers the literal value when choosing type used. Your f() has 2 variants, with different parameter type. When you call f(5) an `int` is passed. You can override the literal default typing by adding specifier U after the value e.g. f(5U). That signifies an `unsigned int`. And you'll have the decrementing f() variant be invoked.
22nd Jul 2020, 5:59 AM
Ipang
0
Okay so my understanding now is that: 1) In our coding environment, the 5 in f(5) provides the declaration and value (aka definition?) of int a = 5, which is the same as signed int a = 5. (or is it assumed that int a was already declared beforehand?) 2) An implicit SIGNED (or physically typed SIGNED) variable CANNOT pass through a function with an unsigned condition.
22nd Jul 2020, 6:28 AM
Solus
Solus - avatar
0
In the first return it will be 6 In the next return it will be 5. So I think output will be 5.
23rd Jul 2020, 1:39 PM
shubham kumar
shubham kumar - avatar