Перечисляемый тип

Function Documentation

void _conio_gettext ( int  left,
int  top,
int  right,
int  bottom,
struct char_info *  buf 
)

Gets text from the screen.

If you haven’t defined prior to including you can use this function also under the name.

See Also
char_info
Parameters
left Left coordinate of the rectangle, inclusive, starting from 1.
top Top coordinate of the rectangle, inclusive, starting from 1.
right Right coordinate of the rectangle, inclusive, starting from 1.
bottom Bottom coordinate of the rectangle, inclusive, starting from 1.
buf You have to pass buffer of size .
void _setcursortype ( int  type )

Sets the cursor type.

See Also
Parameters
type cursor type, under Win32 it is height of the cursor in percents
void clearkeybuf ( void  )

Clears the keyboard buffer.

To see it in effect run and try to press a key during the ‘Flashing…’ phase.

void cputsxy ( int  x,
int  y,
char *  str 
)

Puts string at the specified position.

Parameters
x horizontal position
y vertical position
str string
void delay ( int  ms )

Pauses program execution for a given time.

See Also
Parameters
ms miliseconds
void delline ( void  )

Delete the current line (line on which is cursor) and then moves all lines below one line up.

Lines below the line are moved one line up.

void flashbackground ( int  color,
int  ms 
)

Changes background color for a given time and then it restores it back.

You can use it for visual bell. Does not modify .

See Also
Parameters
color background color
ms miliseconds
char* getpass ( const char *  prompt,
char *  str 
)

Reads password.

This function behaves like cgets.

See Also
Parameters
prompt prompt which will be displayed to user
str string for the password. have to contain length of the — 3
Returns
, the password will be stored in beginning at , in will be length of the string without , at will be \0.
void gettextinfo ( struct text_info *  info )

Returns information of the screen.

See Also
text_info
void gotoxy ( int  x,
int 
)

Moves cursor to the specified position.

Parameters
x horizontal position
y vertical position
void highvideo ( void  )

Makes foreground colors light.

If the current foreground color is less than adds 8 to the its value making dark colors light.

See Also
void inittextinfo ( void  )

Call this if you need real value of normattr attribute in the text_info structure.

See Also
text_info
void insline ( void  )

Insert blank line at the cursor position.

Original content of the line and content of lines below moves one line down. The last line is deleted.

void lowvideo ( void  )

Makes foreground colors dark.

If the current foreground color is higher than substracts 8 from its value making light colors dark.

See Also
void movetext ( int  left,
int  top,
int  right,
int  bottom,
int  destleft,
int  desttop 
)

Copies text.

Parameters
left Left coordinate of the rectangle, inclusive, starting from 1.
top Top coordinate of the rectangle, inclusive, starting from 1.
right Right coordinate of the rectangle, inclusive, starting from 1.
bottom Bottom coordinate of the rectangle, inclusive, starting from 1.
destleft Left coordinate of the destination rectangle.
desttop Top coordinate of the destination rectangle.
void normvideo ( void  )

Sets text attribute back to value it had after program start.

It uses text_info’s normattr value.

See Also
text_info
void putchxy ( int  x,
int  y,
char  ch 
)

Puts char at the specified position.

Parameters
x horizontal position
y vertical position
ch char
void puttext ( int  left,
int  top,
int  right,
int  bottom,
struct char_info *  buf 
)

Puts text back to the screen.

See Also
char_info
Parameters
left Left coordinate of the rectangle, inclusive, starting from 1.
top Top coordinate of the rectangle, inclusive, starting from 1.
right Right coordinate of the rectangle, inclusive, starting from 1.
bottom Bottom coordinate of the rectangle, inclusive, starting from 1.
buf You have to pass buffer of size .
void switchbackground ( int  color )

Replaces background color in the whole window.

The text however is left intact. Does not modify .

See Also
Parameters
color background color
void textattr ( int  _attr )

Sets attribute of text.

Parameters
_attr new text attribute
void textbackground ( int  color )

Sets text background color.

See Also
Parameters
color new background color
void textcolor ( int  color )

Sets text foreground color.

See Also
Parameters
color new foreground color
int wherex ( void  )

Reads the cursor X position.

Returns
cursor X position
int wherey ( void  )

Reads the cursor Y position.

Returns
cursor Y position

Порядок выполнения логических операторов

Рассмотрим выражение

где a, b, c, d – логические значения. Всё выражение равно истине тогда и только тогда, когда все операнды истинны. Если хотя бы один из операндов ложь, то остальные уже не важны. Поэтому, для оптимизации работы, вычисление происходит слева направо и останавливается, как только был найден первый операнд, равный нулю.

В си оператор присваивания может возвращать значение. Иногда он используется непосредственно в условии:

#define _CRT_SECURE_NO_WARNINGS

#include <conio.h>
#include <stdio.h>
#include <stdlib.h>

void main() {
	int a = 0;
	int *p = &a;

	if (a && (p = (int*) malloc(sizeof(int) * 2))) {
		printf("memory was allocated");
	}
	free(p);

	_getch();
}

В данном случае, оператор malloc не будет выполнен, так как первый операнд a равен 0 (соответственно, всё выражение равно нулю). Таким образом, оператор free попытается очистить память, которую не может очистить (т.к. p продолжит ссылаться на a). Если же мы поменяем a = 1, то всё отработает без проблем.

То же самое происходит и при выполнение ||. Выражение

выполняется слева направо до тех пор, пока не встретит первое ненулевое значение. После этого выполнение останавливается, так как известно, что всё выражение равно истине.

Очевидно, что это касается не только оператора присваивания, но и любого другого вызова функции. Например, в этом случае функции foo будет вызвана, bar нет.

#define _CRT_SECURE_NO_WARNINGS

#include <conio.h>
#include <stdio.h>
#include <stdlib.h>

int foo() {
	printf("foo\n");
	return 0;
}

int bar() {
	printf("bar\n");
	return 0;
}

void main() {
	int a = 0, b = 1;

	if (a || foo() || b || bar()) {
		printf("OK\n");
	}
	
	_getch();
}

Вывод – не используйте присваивания и вызовов функций (особенно, если они изменяют состояние программы) внутри условий.

Q&A

Всё ещё не понятно? – пиши вопросы на ящик

Логические операторы

Логические операторы – это операторы, которые принимают в качестве аргументов логические значений (ложь или истину) и возвращают логическое значение. Как и обычные операторы, они могут быть одноместными (унарными, т.е. принимать один аргумент), двуместными (бинарные, принимают два аргумента), трёхместными и т.д.

Особенностью языка си является то, что в нём нет типа, хранящего булево значение (ложь или истину). В си ложью (логическим нулём) считается целочисленный 0, а любое ненулевое целое будет логической истиной. Например

#include <conio.h>
#include <stdio.h>

void main() {
	char boolValue = -71;
	if (boolValue) {
		printf("boolValue is true");
	} else {
		printf("boolValue is false");
	}
	_getch();
}

Логические значения обычно порождаются операторами сравнения (==, !=, >, <, >=. <=).

В языке си представлено три логических оператора: И, ИЛИ и НЕ. Начнём с самого простого

Объявление структуры

Синтаксис объявления структуры

struct  {
	 ;
	 ;
	...
	 ;
};

Например

struct point_t {
	int x;
	int y;
}; //Тут стоит точка с запятой!

Полями структуры могут быть любые объявленные типы, кроме самой структуры этого же типа, но можно хранить указатель на структуру этого типа:

struct node {
	void* value;
	struct node next;
};

Нельзя, нужно

struct node {
	void* value;
	struct node *next;
};

В том случае, если несколько полей имеют один тип, то их можно перечислить через запятую:

struct Point3D {
	int x, y, z;
};

После того, как мы объявили структуру, можно создавать переменную такого типа с использованием служебного слова struct. Доступ до полей структуры осуществляется с
помощью операции точка:

#include <conio.h>
#include <stdio.h>
#include <math.h>

struct point_t {
	int x;
	int y;
};

void main() {
	struct point_t A;
	float distance;

	A.x = 10;
	A.y = 20;

	distance = sqrt((float) (A.x*A.x + A.y*A.y));

	printf("x = %.3f", distance);
	getch();
}

Структура, объявленная в глобальном контексте, видна всем. Структура также может быть объявлена внутри функции:

#include <conio.h>
#include <stdio.h>
#include <math.h>

void main() {
	struct point_t {
		int x;
		int y;
	};
	struct point_t A;
	float distance;

	A.x = 10;
	A.y = 20;

	distance = sqrt((float) (A.x*A.x + A.y*A.y));

	printf("x = %.3f", distance);
	getch();
}

Можно упростить пример: синтаксис языка позволяет создавать экземпляры структуры сразу же после определения:

struct point_t {
		int x;
		int y;
	} A;
	float distance;

Структура также может быть анонимной. Тогда мы не сможем использовать имя структуры в дальнейшем.

#include <conio.h>
#include <stdio.h>
#include <math.h>

void main() {
	struct {
		int x;
		int y;
	} A;
	float distance;

	A.x = 10;
	A.y = 20;

	distance = sqrt((float) (A.x*A.x + A.y*A.y));

	printf("x = %.3f", distance);
	getch();
}

В этом примере мы создали переменную A. Она является структурой с двумя полями.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

Adblock
detector