Jump to content
coisox

Method Invoking

Recommended Posts

Using c++:

int main()

{

cout << " Sum is: " << funct(5);

}

int funct(int y)

{

if (y==1 )

return 1;

else

return y++;

}

Dari program nih, secara logiknye, bagi aku jawapan ialah "sum is: 6". Tapi yg buat aku tak paham, bila aku compile jawapan ialah "sum is: 5". Boley sesaper tolong explain kat aku, kenapa proses penambahan tu tak berlaku. Tak pahamlah! :wacko:

Proses penambahan akan berlaku sekiranya the last two statement (program kat atas) tukar kepada:

else

y++;

return y

Tolooooooonggggg.......

Share this post


Link to post
Share on other sites

Ini dinamakan pre/post increment.

Contoh:

1) jumlah = y++;

Assign value y ke variable jumlah, lepas tu baru lakukan proses increment.

2) jumlah = ++y;

Lakukan proses increment, lepas tu simpan hasil increment y ke variable jumlah

pre/post decrement pun macam tu jugak.

So. Kalau buat:

return y++;

Maknanya kita just return value y sebelum proses increment.

Share this post


Link to post
Share on other sites

return y++;
basically means
return y;
y++; //or ++y; it doesn't matter now.
it does matter. consider
funct(int y)
{
    int i = 2;
    int j = 3;
    return y+i+j; // if y = 5, return value should be 10 
}

compiler akan accumulate hasil tambah semua tu baru return,

sebab y++ tak incremented sebab operator tu post-increment. kalau pre-increment, program akan execute increment value dulu baru return call with value in eax (x86).

Share this post


Link to post
Share on other sites

please use the context above.

after return statement.. it really doesn't matter whether you use post- or pre- increment. Maknanya

return y; 
y++;
dan
return y;
++y;
is just the same thing. Kalau convert directly ke machine code ia akan jadi (secara ringkasnya )
mov eax, [esp+4]
cmp eax, 1
jnz __else
ret
__else:
ret
inc eax

Bermakna inc eax TAK AKAN DILAKSANAKAN. Anything after return statement is useless kalau takde branch pergi ke sana untuk dilaksanakan.

Edited by Paralys3r

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...

×
×
  • Create New...