Skip to content

Instantly share code, notes, and snippets.

@murano500k
Last active June 15, 2017 09:09
Show Gist options
  • Save murano500k/4b15600a20e73762b9498635fc7b4e02 to your computer and use it in GitHub Desktop.
Save murano500k/4b15600a20e73762b9498635fc7b4e02 to your computer and use it in GitHub Desktop.
Operator Precedence
1 :: //Scope resolution
2
a++ a-- //Suffix/postfix increment and decrement
type() //type{} Functional cast
a() //Function call
a[] //Subscript
. -> //Member access
3
++a --a// Prefix increment and decrement
+a -a //Unary plus and minus
! ~ //Logical NOT and bitwise NOT
(type) //C-style cast
*a //Indirection (dereference)
&a //Address-of
sizeof //Size-of[note 1]
new // new[] Dynamic memory allocation
delete // delete[] Dynamic memory deallocation
4 .* ->* //Pointer-to-member
5 a*b a/b a%b// Multiplication, division, and remainder
6 a+b a-b// Addition and subtraction
7 << >> //Bitwise left shift and right shift
8 < <= > >= == !=// For relational operators
10 & //Bitwise AND
11 ^ //Bitwise XOR (exclusive or)
12 | //Bitwise OR (inclusive or)
13 && //Logical AND
14 || //Logical OR
15
a?b:c //Ternary conditional[note 2]
throw //throw operator
= //Direct assignment (provided by default for C++ classes)
+= -= //Compound assignment by sum and difference
*= /= %= //Compound assignment by product, quotient, and remainder
<<= >>= //Compound assignment by bitwise left shift and right shift
&= ^= |= //Compound assignment by bitwise AND, XOR, and OR
16 , //Comma
Type Bytes Range
---------------------------------------------------------------------
short int 2 -32,768 -> +32,767 (32kb)
unsigned short int 2 0 -> +65,535 (64Kb)
unsigned int 4 0 -> +4,294,967,295 ( 4Gb)
int 4 -2,147,483,648 -> +2,147,483,647 ( 2Gb)
long int 4 -2,147,483,648 -> +2,147,483,647 ( 2Gb)
signed char 1 -128 -> +127
unsigned char 1 0 -> +255
float 4
double 8
long double 12
Data Type Initialser
int 0
char '\0'
float 0
pointer NULL
auto //- default
register// - not in RAM, size=word, no & op
static// - 'seen' within all functions in this source file
extern// - visible to ALL the program files
Pointers
const int * const ip; /* The pointer *ip is const and it points at is also cont */
int * const ip; /* The pointer *ip is const */
const int * ip; /* What *ip is pointing at is const */
int * ip; /* Nothing is const */
typedef struct{
char firstName[20];
char lastName[20];
char SSN[10];
float gpa;
}student;
/*You can create arrays of structs.
Structs can be copied or assigned.
The & operator may be used with structs to show addresses.
Structs can be passed into functions. Structs can also be returned from functions.
Structs cannot be compared!
Structures can store non-homogenous data types into a single collection, much like an array does for common data (except it isn't accessed in the same manner).
Pointers to structs have a special infix operator: -> for dereferencing the pointer.
typedef can help you clear your code up and can help save some keystrokes.*/
Memory Management Functions
void *calloc(int num elems, int elem_size); //Allocate an array and initialise all elements to zero
void free(void *mem address); //Free a block of memory.
void *malloc(int num bytes); //Allocate a block of memory.
void *realloc(void *mem address, int newsize); //Reallocate (adjust size) a block of memory.
Buffer Manipulation
void* memcpy(void* s, const void* ct, int n); //Copies n characters from ct to s and returns s. s may be corrupted if objects overlap.
int memcmp(const void* cs, const void* ct, int n); //Compares at most (the first) n characters of cs and ct, returning negative value if cs<ct, zero if cs==ct, positive value if cs>ct.
void* memchr(const void* cs, int c, int n); //Returns pointer to first occurrence of c in first n characters of cs, or NULL if not found.
void* memset(void* s, int c, int n); //Replaces each of the first n characters of s by c and returns s.
void* memmove(void* s, const void* ct, int n); //Copies n characters from ct to s and returns s. s will not be corrupted if objects overlap.
Error Handling Functions
void perror(const char *s); //produces a message on standard error output describing the last error encountered.
char *strerror(int errnum ); //returns a string describing the error code passed in the argument errnum.
File Functions
FILE *fopen(const char *filename, const char *mode);
int fclose(FILE *a_file);
int fgetc (FILE *fp);
int fputc( int c, FILE *fp );
size_t fread(void *ptr, size_t size_of_elements, size_t number_of_elements, FILE *a_file);
size_t fwrite(const void *ptr, size_t size_of_elements, size_t number_of_elements, FILE *a_file);
/*
w - open for writing (file need not exist)
a - open for appending (file need not exist)
r+ - open for reading and writing, start at beginning
w+ - open for reading and writing (overwrite file)
a+ - open for reading and writing (append if file exists)
*/
String Manipulation Functions
char *strcpy (char *dest, char *src); //Copy src string into dest string.
char *strncpy(char *string1, char *string2, int n); //Copy first n characters of string2 to stringl
int strcmp(char *string1, char *string2); //Compare string1 and string2 to determine alphabetic order.
int strncmp(char *string1, char *string2, int n); //Compare first n characters of two strings.
int strlen(char *string); //Determine the length of a string.
char *strcat(char *dest, const char *src); //Concatenate string src to the string dest.
char *strncat(char *dest, const char *src, int n); //Concatenate n chracters from string src to the string dest.
char *strchr(char *string, int c); //Find first occurrence of character c in string.
char *strrchr(char *string, int c); //Find last occurrence of character c in string.
char *strstr(char *string2, char string*1); //Find first occurrence of string string1 in string2.
char *strtok(char *s, const char *delim) ; //Parse the string s into tokens using delim as delimiter.
Character Functions
int isalnum(int c); //The function returns nonzero if c is alphanumeric
int isalpha(int c); //The function returns nonzero if c is alphabetic only
int iscntrl(int c); //The function returns nonzero if c is a control chracter
int isdigit(int c); //The function returns nonzero if c is a numeric digit
int isgraph(int c); //The function returns nonzero if c is any character for which either isalnum or ispunct returns nonzero.
int islower(int c); //The function returns nonzero if c is a lower case character.
int isprint(int c); //The function returns nonzero if c is space or a character for which isgraph returns nonzero.
int ispunct(int c); //The function returns nonzero if c is punctuation
int isspace(int c); //The function returns nonzero if c is space character
int isupper(int c); //The function returns nonzero if c is upper case character
int isxdigit(int c); //The function returns nonzero if c is hexa digit
int tolower(int c); //The function returns the corresponding lowercase letter if one exists and if isupper(c); otherwise, it returns c.
int toupper(int c); //The function returns the corresponding uppercase letter if one exists and if islower(c); otherwise, it returns c.
printf
%d //print an int argument in decimal
%ld //print a long int argument in decimal
%c //print a character
%s //print a string
%f //print a float or double argument
%e //same as %f, but use exponential notation
%g //use %e or %f, whichever is better
%o //print an int argument in octal (base 8)
%x //print an int argument in hexadecimal (base 16)
%% //print a single %
Special characters/*
\' single quote byte 0x27 (in ASCII encoding)
\" double quote byte 0x22 (in ASCII encoding)*/
\? //question mark byte 0x3f (in ASCII encoding)
\\ //backslash byte 0x5c (in ASCII encoding)
\a //audible bell byte 0x07 (in ASCII encoding)
\b //backspace byte 0x08 (in ASCII encoding)
\f //form feed - new page byte 0x0c (in ASCII encoding)
\n //line feed - new line byte 0x0a (in ASCII encoding)
\r //carriage return byte 0x0d (in ASCII encoding)
\t //horizontal tab byte 0x09 (in ASCII encoding)
\v //vertical tab byte 0x0b (in ASCII encoding)
\nnn //arbitrary octal value byte nnn
\xnn //arbitrary hexadecimal value byte nn
\unnnn //Unicode character that is not in the basic character set.
\Unnnnnnnn //Unicode character that is not in the basic character set.
#include <stdio.>h
main( int argc, char *argv[] )
{
if( argc == 2 )
printf("The argument supplied is %s\n", argv[1]);
else if( argc > 2 )
printf("Too many arguments supplied.\n");
else
printf("One argument expected.\n");
}
y = x/*p /* sets y to the value of x */;
y = x / *p; /* divides x over value pointeed by p */
y = x /(*p); /* divides x over value pointeed by p */
a=-1; /* a = a - 1 for old compiler, a = -1 for newer compilers */
a=/*b; /* a = a/(*b) for some old compilers, comment for newer ones */
p - > a; /* illegal */
printf('\n'); /* fails at run-time */
char *a = 'yes'; /* 'yes' is integer composed of values 'y', 'e', 's',
typecasted to char */
char *a = "yes"; /* string with three characters and null terminated,
in read-only data memory. Cannot change */
char a[] = yes; /* string in read-only data memory. Copied to stack,
so it can change */
if (flags & FLAG != 0) /* equivalent to if (flags & (FLAG !=0)) */
r = h<<4 + l; /* equivalent to r = h << (4 + l); */
/* operator precedence:
1: func call (),
2: unary operators (++, --,
3: binary operators (<<, &&, =
4: ternary operator ( cond ? a: b )
4: comma
*/
if (a < b == c < d) /* equivalent to (a<b) == (c<d) */ while (c=getc(in) != EOF) /* assignment lower preference than comparison so equivalent to c = (getc(in) != EOF), which is true or false */ if (x[i] > big); /* equivalent to if (x[i] > big) { }, which is { } */
struct foo {
int x;
}
f() {
... } /* f returns type struct foo */
func(); /* calls function */
func; /* evaluates address of function */
i = 0;
while (i < n)
y[i] = x[i++]; /* wrong (maybe): no guarantee that y[i] is
evaluated before i incremented. */
i = 0;
while (i < n)
y[i++] = x[i]; /* wrong (maybe): same as previous */
i = 0;
while (i < n) {
y[i] = x[i];
i++;
} /* works fine */
for (i = 0; i < n; i++) y[i] = x[i]; /* works fine */ /* biwise operators: &, |, ~ -> arguments per bit
logical operators: &&, ||, ! -> arguments true or false
*/
/* it works, but shouldn't be used. It should be && */
i = 0;
while (i < tabsize & tab[i] != x)
i++;
/* if big-endian (MSB to lower addr), a[10] is actually i,
so this turns out to be an infinite loop */
int i, a[10];
for (i=1; i<=10; i++)
a[i] = 0;
/* fails because '2' is an integer. It should be '2.0'
conversion rules:
- integer values shorter than an int are converted to int
- floating-point values shorter than a double are converted to double.
- All other values are left unconverted.
Actually, using the <math.h> this would work. It looks like the
library function can checks for the type and typecasts automatically
*/
double sqrt(double a);
double s;
s = sqrt (2);
printf ("%g\n", s);
/* there is no integer to float conversion. Typecasting is required
But if one of the numbers in the operation is float, then the result
of the operation is float. */
int main() {
int a = 3/2;
printf("%d\n", a); /* 1 */
float f = 3/2;
printf("%f\n", f); /* 1.000000 */
float g = 3.0/2.0;
printf("%f\n", g); /* 1.500000 The same if 3.0/2 or 3/2.0 */
float h = (float)(3/2);
printf("%f\n", h); /* 1.000000 */
float j = (float)3/2;
printf("%f\n", j); /* 1.500000 */
float k = 3/(float)2;
printf("%f\n", k); /* 1.500000 */
return 0;
}
/* scanf expects pointer to integer. This might work for some smart compilers,
For some compiler, if given 5 values, output is 0 0 0 0 0 1 2 3 4
Storing c in char might overwrite i in big endian. So every time a value is
entered, it resets i
*/
main() {
int i;
char c;
for (i=0; i<5; i++) {
scanf ("%d", &c);
printf ("%d ", i);
}
printf ("\n");
}
/* fails because r doesnt have memory allocated */
char *r;
strcpy (r, s);
strcat (r, t);
/* might fail if r is not big enough */
char r[100];
strcpy (r, s);
strcat (r, t);
/* fails because it r needs one more space for null termination
and it doesnt check if malloc worked */
char *r;
r = malloc (strlen(s) + strlen(t));
strcpy (r, s);
strcat (r, t);
/* should work */
char *r;
r = malloc (strlen(s) + strlen(t) + 1);
if (!r)
exit (1);
strcpy (r, s);
strcat (r, t);
int main() {
char *p, *q;
p = "xyz";
q = p;
q[1] = "Y"; // compile-time error: assigning addr to char type
q = 'Y'; // run-time error: Bus error 10 (cant change string
// literals, they are read-only mem
// commenting previous two lines works
printf("%s\n", p);
printf("%s\n", q);
return 0;
}
char *p = NULL;
if (p == (char *) 0) // valid
if (strcmp (p, (char *) 0) == 0) // invalid, it deferences null pointer
printf (p); // invalid
printf ("%s", p); // invalid
/* unsigned overflow wraps around
signed overflow is undefined
Wrong way to check if two positive signed integers overflow when summed
*/
if (a + b < 0)
overflow();
/* Right way to check overflow of two positive integers */
if ((int) ((unsigned) a + (unsigned) b) < 0)
overflow();
/* wrong undefined behavior. getchar returns int, because it needs to
be able to return any char, plus EOF. So, depending on the compiler,
it may never be able to return EOF if return typecasted to EOF
*/
char c;
while ((c = getchar()) != EOF)
putchar (c);
/* parenthesis in macro protect in case an expression
is passed as arg to the macro, and there is an operator
in the expression with higher preference than the < in the macro This macro evaluates each argument twice. So the i is incremented twice */ #define max(a,b) ((a)>(b)?(a):(b))
biggest = x[0];
i = 1;
while (i < n) biggest = max (biggest, x[i++]); #define putc(x,p) (--(p)->_cnt>=0 ? (*(p)->_ptr++=(x)) : _flsbuf(x,p))
putc(c,*f++); /* might fail, because p argument is evaluated twice */
putc(*c++, f); /* works, because x is evaluated only once. It shows up
at both sides of the ternary operator, but only one
of them will be executed */
#define toupper(c) ((c)>=’a’ && (c)<=’z’? (c)+(’A’-’a’): (c))
toupper(*p++); /* might fail */
#define T1 struct foo *
T1 a, b; /* expands to struct foo *a, b;
a is 'struct foo *a' but b is 'struct foo b'
*/
typedef struct foo *T2;
T2 a, b; /* works fine (two pointers to struct foo) */
char a = 0xFF;
int b = (int)a; /* char might be signed or unsigned. if treated as signed
the int will be negative. Otherwise it wont
To make sure define as 'unsigned char',
unsigned char 0 to 255
signed char -128 to 127
*/
/* n negative would break things */
int n;
h = n % HASHSIZE;
/* fix: */
unsigned n;
/* or */
h = n % HASHSIZE;
if (h < 0) h += HASHSIZE; /* breaks it upper passed to toupper */ #define toupper(c) ((c)+’A’-’a’)
#define tolower(c) ((c)+’a’-’A’) /* evaluates multiple times the argument */
#define toupper(c) ((c) >= ’a’ && (c) <= ’z’? (c) + ’A’ - ’a’: (c))
#define tolower(c) ((c) >= ’A’ && (c) <= ’Z’? (c) + ’a’ - ’A’: (c))
if(a=b) c; /* a always equals b, but c will be executed if b!=0 */
if( 0 < a < 5) c; /* 0<a generates 0 or 1, which is always less than 5
so this is always false */
if( a =! b) c; /* assigns !b to a, and evaluates !b for the if */
switch (a) {
int var = 1; /* This line never runs */
case A: ...
case B: ...
}
//#####################################################
Useful links
http://www.learntosolveit.com/cprogramming/ //k&r solutions
Tutorials
http://beej.us/guide/bgc/output/html/multipage/index.html
http://www.geeksforgeeks.org/c/
https://www.eskimo.com/~scs/cclass/notes/
Выравнивание структур
По указателю или по наибольшему
смотрим на
A static variable inside a function keeps its value between invocations.
A static global variable or a function is "seen" only in the file it's declared in
http://www.cs.columbia.edu/~hgs/os/sync.html - sync primitives
cplusplus.com
cppreference.com
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment