Sizeof?
#1

Good morning.

The sizeof() changes what?

For example, between the two codes that I will present to you:

pawn Код:
for (new i = 1; i <= totalcars; i++)
And:

pawn Код:
for (new i = 1; i <= sizeof(totalcars); i++)
Thx !!
Reply
#2

https://sampwiki.blast.hk/wiki/Sizeof#sizeof

You bassicaly use sizeof to get the elements of an array. Like:
new cars[1000];
sizeof(cars)=1000

So if in your example "totalcars" is an integer i think you'll get an error or at least a warning.

Edit: Nope. It won't show you any warning or error. Just that the script won't work alright since sizeof(anyinteger) is 1.
Reply
#3

I have:

new totalcars = 0;

Therefore the use of sizeof is good in this case?
Reply
#4

It depends.

For example, if you want to loop through all the indexes of an array, using sizeof will be correct (not that it shouldn't be "<= sizeof (...);" because that will cause run time error 4. You'll need to use either "<" or "!=". Also indexes on arrays start always from 0 and not 1.

If you have an array (such as for houses - an example) and you want to loop only through the houses that exist, then if you store in a global variable how many houses there are, you can loop using the first one (without the '=' sign as I mentioned above).
Reply
#5

Quote:
Originally Posted by TheSy
Посмотреть сообщение
I have:

new totalcars = 0;

Therefore the use of sizeof is good in this case?
Depends. Using sizeof(totalcars) will give you either 1, 2 or 4 (probably 4 knowing Pawn's scrumptious memory consumption habits) - because it returns the size of the data type used for the 'totalcars' variable. It will automatically be converted to a number on compilation, so it is equivalent to typing '4', but it is dependent on the type it's getting the size of, so it's much preferred. *citation needed

With an array its behaviour is slightly different, as it will instead count the number of elements, instead of the exact size of memory consumption. If you're dynamically counting the number of vehicles inside 'totalcars' already, you only need to use the variable itself.


EDIT: Ninja'd on "depends", hah.
Reply


Forum Jump:


Users browsing this thread: 1 Guest(s)