Monday, January 26, 2009

Functions; Comments

Suppose we want, as part of a larger program, to count the occurrences of the ascii characters in some input text. Let us also map illegal characters (those with value>127 or <0) into one pile. Since this is presumably an isolated part of the program, good practice dictates making it a separate function. Here is one way:

main( )
{
int hist[129]; /* 128 legal chars + 1 illegal group*/
...
count(hist, 128); /* count the letters into hist */
printf( ... ); /* comments look like this; use them */
... /* anywhere blanks, tabs or newlines could appear */
}

count(buf, size)
int size, buf[ ]; {
int i, c;
for( i=0; i<=size; i++ )
buf[i] = 0; /* set buf to zero */
while( (c=getchar( )) != '\0' ) { /* read til eof */
if( c > size || c < 0 )
c = size; /* fix illegal input */
buf[c]++;
}
return;
}

We have already seen many examples of calling a function, so let us concentrate on how to define one. Since count has two arguments, we need to declare them, as shown, giving their types, and in the case of buf, the fact that it is an array. The declarations of arguments go between the argument list and the opening `{'. There is no need to specify the size of the array buf, for it is defined outside of count.
The return statement simply says to go back to the calling routine. In fact, we could have omitted it, since a return is implied at the end of a function.
What if we wanted count to return a value, say the number of characters read? The return statement allows for this too:

int i, c, nchar;
nchar = 0;
...
while( (c=getchar( )) != '\0' ) {
if( c > size || c < 0 )
c = size;
buf[c]++;
nchar++;
}
return(nchar);

Any expression can appear within the parentheses. Here is a function to compute the minimum of two integers:

min(a, b)
int a, b; {
return( a < b ? a : b );
}

To copy a character array, we could write the function

strcopy(s1, s2) /* copies s1 to s2 */
char s1[ ], s2[ ]; {
int i;
for( i = 0; (s2[i] = s1[i]) != '\0'; i++ );
}

As is often the case, all the work is done by the assignment statement embedded in the test part of the for. Again, the declarations of the arguments s1 and s2 omit the sizes, because they don't matter to strcopy. (In the section on pointers, we will see a more efficient way to do a string copy.)
There is a subtlety in function usage which can trap the unsuspecting Fortran programmer. Simple variables (not arrays) are passed in C by ``call by value'', which means that the called function is given a copy of its arguments, and doesn't know their addresses. This makes it impossible to change the value of one of the actual input arguments.
There are two ways out of this dilemma. One is to make special arrangements to pass to the function the address of a variable instead of its value. The other is to make the variable a global or external variable, which is known to each function by its name. We will discuss both possibilities in the next few sections.

4 comments:

  1. Консоли от корпорации Microsoft не сразу завоевали всемирную популярность и доверие игроков. 1-ая консоль под названием Xbox, вышедшая в далеком 2001 году, существенно уступала PlayStation 2 по количеству проданных приставок. Но все поменялось с выходом Xbox 360 - консоли седьмого поколения, которая стала по-настоящему "народной" для обитателей России и государств СНГ - Игры для Xbox 360. Сайт Ru-Xbox.Ru является пользующимся популярностью ресурсом среди поклонников приставки, так как он предлагает игры для Xbox 360, которые поддерживают все существующие версии прошивок - совершенно бесплатно! Зачем играть на оригинальном железе, в случае если есть эмуляторы? Для Xbox 360 игры выходили длительное время и представлены как посредственными проектами, так и хитами, многие из которых даже сейчас остаются уникальными для это консоли. Некие пользователи, желающие сыграть в игры для Xbox 360, смогут задать вопрос: зачем нужны игры для прошитых Xbox 360 freeboot или различными версиями LT, в случае если имеется эмулятор? Рабочий эмулятор Xbox 360 хоть и существует, но он просит производительного ПК, для покупки которого будет нужно вложить существенную сумму. К тому же, разнообразные артефакты в виде исчезающих текстур, недостатка некоторых графических эффектов и освещения - могут значительно испортить впечатления об игре и отбить желание для ее предстоящего прохождения. Что предлагает этот веб-сайт? Наш интернет-сайт на сто процентов приурочен к играм для приставки Xbox 360. У нас вы можете совершенно бесплатно и без регистрации скачать игры на Xbox 360 через torrent для следующих версий прошивок консоли: - FreeBoot; - LT 3.0; - LT 2.0; - LT 1.9. Каждая прошивка имеет свои особенности обхода встроенной защиты. Поэтому, для запуска той либо другой игры потребуется скачать специальную ее версию, которая вполне адаптирована под одну из четырех вышеперечисленных прошивок. На нашем интернет-сайте можно без усилий подобрать желаемый проект под подходящую прошивку, так как возле каждой игры находится заглавие версии (FreeBoot, LT 3.0/2.0/1.9), под которую она адаптирована. Пользователям данного ресурса доступна особая категория игр для 360-го, созданных для Kinect - специального дополнения, которое считывает все движения 1-го либо нескольких игроков, и позволяет управлять с помощью их компьютерными персонажами. Большой выбор ПО Кроме возможности загрузить игры на Xbox 360 Freeboot или LT различных версий, тут вы можете получить программное обеспечение для консоли от Майкрософт: - современные версии Dashboard, которые позволяют кастомизировать интерфейс консоли под свои нужды, сделав его более комфортным и современным; - браузеры; - просмотрщики файлов; - сохранения для игр; - темы для консоли; - программы, для конвертации образов и записи их на диск. Кроме перечисленного выше игры на Xbox 360 Freeboot можно запускать не с дисковых, а с USB и многих других носителей, используя программу x360key, которую можно достать на нашем сайте. Посетителям доступно множество полезных статей, а кроме этого форум, где можно пообщаться с единомышленниками либо попросить совета у более опытных владельцев консоли.

    ReplyDelete
  2. Your car could be stolen if you don't remember this!

    Imagine that your car was taken! When you visit the police, they inquire about a particular "VIN search"

    A VIN decoder: What is it?

    Similar to a passport, the "VIN decoder" allows you to find out the date of the car's birth and the identity of its "parent" (manufacturing facility). You can also find out:

    1.Type of engine

    2.Model of a car

    3.The DMV's limitations

    4.Number of drivers in this vehicle

    The location of the car will be visible to you, and keeping in mind the code ensures your safety. The code can be examined in the online database. The VIN is situated on various parts of the car to make it harder for thieves to steal, such as the first person sitting on the floor, the frame (often in trucks and SUVs), the spar, and other areas.

    What if the VIN is intentionally harmed?

    There are numerous circumstances that can result in VIN damage, but failing to have one will have unpleasant repercussions because it is illegal to intentionally harm a VIN in order to avoid going to jail or calling the police. You could receive a fine of up to 80,000 rubles or spend two years in prison. You might be stopped by an instructor on the road.

    Conclusion.

    The VIN decoder may help to save your car from theft. But where can you check the car reality? This is why we exist– VIN decoders!

    ReplyDelete
  3. If you don't remember this, your car may be stolen!

    Imagine that your car was taken! When you visit the police, they inquire about a specific "VIN lookup"

    A VIN decoder is what?

    Similar to a passport, the "VIN decoder" allows you to find out when the car was born and who its "parent"( manufacturing plant) is. Additionally, you can find:

    1.Type of engine

    2.Automobile model

    3.The DMV's limitations

    4.The number of drivers in this vehicle

    You will be able to locate the car, and keeping in mind the code ensures your safety. The code can be checked in the database online. The VIN is situated on various parts of the car to make it harder for thieves to steal, such as the first person's seat on the floor, the frame (often in trucks and SUVs), the spar, and other areas.

    What happens if the VIN is harmed on purpose?

    There are numerous circumstances that can result in VIN damage, but failing to have one will have unpleasant repercussions because it is illegal to intentionally harm a VIN in order to avoid going to jail or being arrested by the police. You could receive a fine of up to 80,000 rubles and spend two years in prison. You might be held up on the road by a teacher.

    Conclusion.

    The VIN decoder may help to save your car from theft. But where can you check the car reality? This is why we exist– VIN decoders!

    ReplyDelete