Forum > Beginners

"const" as a method parameter [SOLVED]

(1/4) > >>

I saw some methods have "const" as parameters, but I know that methods take variables as parameters, so what does that mean or how it works or what is the difference - for example - between the next empty two functions I made to test the acceptance of the compiler to the "const" type as a parameter:

--- Code: Pascal  [+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i < x.length; i++) { x[i].style.maxHeight='none'; x[i].style.height = Math.min(x[i].clientHeight+15,306)+'px'; x[i].style.resize = "vertical";}};} ---function func1(c:char):char;function func2(const c:char):char;  function func1(c:char):char;begin   func1:=c;end; function func2(const c:char):char;begin   func2:=c;end;       

Look at this:
And this:

إن لم يستبن الفرق لم يكن هناكـ إختلاف في الأثر

google translate:
If the difference is not identified, then there is no difference in the effect

I didn't get the difference, maybe the problem is my weak English, do you know the difference?


If you were a BASIC user then you may notice Pascal runs faster. That happens because Pascal generated binaries are optimized.

Const parameter is one of them to used for producing optimized binary. If the compiler finds it, it will perform some necessary optimizations.

String is slow, it involves many processes especially for duplicating the data in memory. You usually will see const are used for string parameters.

1. function isSomethingInTheText(const Something, TheText: string): Boolean;
2. function isSomethingInTheText(Something, TheText: string): Boolean;

The function #1 is a lot faster than the second one. Because it tells the compiler not to generate the code for duplicating the data in memory.

Now, you may ask. Why the compiler does not automatically make it as a const parameter if the data does not change in the function/procedure. That will be great, unfortunately the compiler isn't so smart.

Fix some typing error.

Besides what Handodo was saying, let me note that the most prominent difference for all kinds of types is that you are not allowed to change the "const" parameter inside the function (*). So, if you need, for example, the next character and call c := succ(c) this is only possible in func1, but not in func2. Therefore, using "const" is a good documentation tool to indicate already in the signature of a function "hey, don't care about this parameter, it will not change."

(*) Hmmm, not completely exact: When the parameter is a class you ARE allowed to change properties. Quite confusing...


[0] Message Index

[#] Next page

Go to full version