--i not equal to i - 1 ???
-
In the following function replacing "number - 1" does not yield the same correct result as "--number"? Why is that so? Am I'm missing something? int sum( int number ) { int result; if (number == 1) return number; else { result = sum(number - 1) + number; return result; } }
-
In the following function replacing "number - 1" does not yield the same correct result as "--number"? Why is that so? Am I'm missing something? int sum( int number ) { int result; if (number == 1) return number; else { result = sum(number - 1) + number; return result; } }
--number changes the value of number, number - 1 does not. say number is 10:
sum(number - 1) + number;
issum(9) + 10;
andsum(--number) + number;
issum(9) + 9;
You may be right I may be crazy -- Billy Joel -- Within you lies the power for good - Use it!
-
--number changes the value of number, number - 1 does not. say number is 10:
sum(number - 1) + number;
issum(9) + 10;
andsum(--number) + number;
issum(9) + 9;
You may be right I may be crazy -- Billy Joel -- Within you lies the power for good - Use it!
-
--number changes the value of number, number - 1 does not. say number is 10:
sum(number - 1) + number;
issum(9) + 10;
andsum(--number) + number;
issum(9) + 9;
You may be right I may be crazy -- Billy Joel -- Within you lies the power for good - Use it!
Being a bit pedantic here (but it's necessary!)... Since the order of evaluation is not defined by the language spec, the compiler writer is free to choose, so your second example
sum(--number) + number;
could come out either way (butnumber
will always wind up decremented). There are lots of examples of confusion over this. Cheers, Peter [edit]formatting[/edit]Software rusts. Simon Stephenson, ca 1994.
-
Being a bit pedantic here (but it's necessary!)... Since the order of evaluation is not defined by the language spec, the compiler writer is free to choose, so your second example
sum(--number) + number;
could come out either way (butnumber
will always wind up decremented). There are lots of examples of confusion over this. Cheers, Peter [edit]formatting[/edit]Software rusts. Simon Stephenson, ca 1994.
I concur, at least for C. I just don't know for recent versions of C++. And I would never write a statement like that. :)
Luc Pattyn [Forum Guidelines] [My Articles] Nil Volentibus Arduum
Please use <PRE> tags for code snippets, they preserve indentation, improve readability, and make me actually look at the code.
-
I concur, at least for C. I just don't know for recent versions of C++. And I would never write a statement like that. :)
Luc Pattyn [Forum Guidelines] [My Articles] Nil Volentibus Arduum
Please use <PRE> tags for code snippets, they preserve indentation, improve readability, and make me actually look at the code.
According to this list, item 31 (on the table of contents), it is true for C++ as well.