Changes

Jump to: navigation, search

Langage C

21,560 bytes added, 23:08, 15 April 2023
/* liens : documentation Site Internet */
En se basant sur le livre "'''Le langage C'''" de Tony Zang, une idée est venue d'y faire les exercices mais en réalisant un vrai programme en mode console et qui par la suite peut évoluer en mode graphique, ou autres, mais allons par étapes... avec d'autres rajouts toujours autour du langage C.
 
Les programmes, que soit sous un environnement Linux, Mac ou Windows, sont lancé par un fichier qu'on appelle "'''exécutable'''" (fichier binaire) qui ne sera compris que par nos PC. Il y a 3 phases pour créer un fichier exécutable :
1/ éditer dans un fichier texte notre code que ce soit en C, en VB, en python, etc... dans notre cas, ces ou ces fichiers par une extension ".c" ou ".h". On appelle ça des fichiers '''sources'''
2/ ensuite on va utiliser un compilateur (dans notre cas C) qui va traduire les instructions écrites en un fichier de type '''objet'''
3/ ensuite on utilisera un '''éditeur de lien (linker)''' qui va associé des bibliothèques d'objet pour créer notre fichier "exécutable"
 
ATTENTION: On ne peut pas transférer un exécutable d'un machine à une autre sans recompiler et linker les fichiers sources, surtout si on passe d'un système d'exploitation à un autre.
Ce wiki ne se veut pas un cours de C ou un tuto mais plutôt un projet autour de l'apprentissage du langage C.
On the book "'''Le langage C'''" of Tony Zang, an idea is come to make the all exercices but to realize a complet program in consol mode in a first time.
 
The programs, under linux, Mac or Windows, are activated by a file called "''' executable ''' (binary file)", only our PC can understand this file ;-). There are 3 phases to create this file :
1/ edit your code (C, VB, Java, other) in file text with for C language ".c" or ".h" extension. These files are called "'''source file'''"
2/ using a compiler (here the C compiler) which translate the C instructions writting in the source file, in the "'''object'''" files
3/ using after a linker which will unite the object file and object library to create an executable file
 
WARNING: It is not possible to transfer an executable file from one PC to another. It must recompile and link the source files on each PC.
 
This wiki is not a cours or a tuto, just a project arround of C langage.
=> Le langage haut niveau est langage qui peut être interpréter par l'homme. Le C est un langage haut niveau
comme le langage C est de type haut niveau, il faudra le compiler avec un compiler pour que la machine puisse l'interpréter (langage bas niveau). Il faudra le faire sur chaque machine ou l'on travaille
''In English :''
=> High language is a language which can be interpreted by a person. The C language is of high type.
the language C is of high level, it would using a compiler for that the device undertsand the language (down level)and make this operation on each device (PC) where we work.
=== chapter 2 (résumé) ===
 
''In french'' : dans ce chapitre, sont vue les notions de directive (inclue), de fichier d'en-tête (header file -> .h), de commentaire (// ou /* */), de la fonction principale '''MAIN''', de la fonction ''EXIT'', du saut de ligne ('\n')...
 
''In English'': in this chapter, we see the concepts of commandes (include), of header file (.h), of commentaries (// or /* */), of principale function '''MAIN''' and the function ''EXIT'', of line break ('\n')...
==== code part ====
structur to begin a C programme
 
#include <stdio.h> // entrée - sortie
int main()
{
return 0;
}
==== Trick ====
 
1) ''In french'' : en C, les commentaires officielle se notent de cette manière :
 
''In English'': In C, the official commentaries wrote in this manner
/* ceci est un commentaire officiel */
 
''In french'' : mais on peut aussi voir des commentaires de comme ceci, même si cela ne fait pas partie de la norme '''ANSI'', mais accepté par de nombreux compilateurs:
 
''In English'': we can see also commentaries displayed like below, but it is not in the '''ANSI'' norm, same if more compilators agree that.
// ceci est aussi un commentaire
 
''In french'' : les commentaires n'ont pas d'influence sur la taille ou sur le fonctionnement du fichier exécutable
 
''In English'': The commentaries are not influence on the size or the funtions of executable file.
 
2) ''In french'': la fonction "Main" est type '''int''', c'est-à-dire qu'elle renvoie une valeur entière. Pour retourner une valeur d'une fonction, on utilise l'instruction '''return'''. Si celle-ci retourne '0', cela veut dire que le programme s'est fini correctement, sinon cela veut dire qu'il y a eu une erreur dans le programme.
 
''In English'': The "Main" function is kind integer, it means that it returns a integer value. To return a value in a function, we use the '''return''' instruction. if this value is '0', the programm finished correctly but if the value is different, there is an error in the program.
 
3) ''In French'' : En C, on va aussi associé des fichier de type header-file ou fichier d'entête (.h) qui permettront d'appeler des fonctions déjà créer comme : '''printf()''' ou '''sin()''',... pour ce faire on utilise la directive "'''#include'''". On trouvera deux façons de les écrire
 
'' In English'' : In C, we associate some header file (.h) which allow to call different functions already created like : '''printf()''' or '''sin()'''... To use these libraries, it must use the directive : "'''#include'''". Here two method to write that :
1) #include <nom_lib.h> indicate at the preprocesseur that the search of this library must be ouside the current directories where is save the global project
2) #include "nom_lib.h" indicate at the preprocesseur that the search of this library must be inside the current directoires
 
=== chapter 3 (résumé) ===
''In French'' : dans ce chapitre on voit la notion de constante ou de variable, de types, on voit aussi les notions d'expression et d'instruction, les notions de fonctions et d'arguments ainsi que les appels de fonction.
 
'' In English'' : in this chapter, these different subjects will be seen : constant / variable / type / expression / instruction / function / argument / and call of functions
 
==== code part ====
an exemple of instruction with a constante and a variable:
i = 100;
''IN french:'' i représente une variable | le nombre 100 représente une constante
 
''In English:'' i depicts a variable | the 100 number depicts a constant
 
an other examples showing the type declaration, the instructions, the expressions, the constantes and the variables
int i; // declaration of integer variable
int j = 10; // declaration of integer variable where a constant associate to him
int x, y, z; // declaration of integer variable
// example of instruction with an expression (side right)
x = j + 5;
y = j + x + 10;
z = j / 2
i = (x - y) / z;
 
==== Trick ====
 
''rules for the nomination of variables or functions'':
 
* A name of V/F don't begin by a number
* A name of V/F don't begin by a mathemtics symbole (+ / -...) or a '*' or '.'
* A name of V/F don't begin or include a num '-' or ' ' '
 
<u>Remark</u>: a name which begins by '_'namevar is correct
 
=== chapter 4 (résumé) ===
''In French'' : dans ce chapitre seront les notions de type (char, int, float, double,...)
 
'' In English'' in this chapter, the notions of type (char, int, float, double,...) will see
 
==== code part ====
===== Type Char =====
 
''In French'': représente une variable de 8bits : <math>2^8</math> utilisé en rapport avec la table ASCII qui représente 256 caractères
 
''In English'': is a variable of 8bits : <math>2^8</math> using especially with ASCII table (256 charaters)
<u>exemple</u>:
char var_name;
var_name = 'B' // enregistre un caractère
var_name = 0x30; // représente le nombre '0' en caractère
 
===== Type Int =====
 
''In French'': variable représentant un nombre entier (sans virgule) généralement codé sur 16bits (voir 32bits), ce qui fait un nombre pouvant aller de 32767 à -32768
 
''In English''. Variable which is an integer (without comma) currently coded on 16bits (see 32bits). This number can go to 32767 à -32768
 
<u>exemple</u>:
int var_int;
var_int = 5 // enregistre un nombre
var_int = 5 + 36; // mémorise un formule mathématique
 
===== Type float =====
 
''In french'': représente un nombre réel (aussi appelé nombre flottant en programmation), cette variable est codée sous 32bits
 
'' In English'': is a real number (also called float number in programming). This variable is coded on 32bits.
 
<u>exemple</u>:
float pi, div;
pi = 3.14 // enregistre un nombre à virgule
div = 52.2 / 53; // mémorise un formule mathématique
 
==== Trick ====
 
''in French'' : Il y a au minium 32 "Mots Clés" qui sont réservés pour le compilateurs, ce sont des mots que nous ne pouvons pas utilisé comme nom de variable ou nom de fonction (voir sous la rubrique '''liens utiles''').
 
'' In English'': There are 32 "Key Word" to minimum in langage C where we don't use these like variable name or function name (see the chapter '''liens utiles''').
 
=== chapter 5 (résumé) ===
''In French'': ce chapitre parle des entrées - sorties standard avec les fonctions de type getc(), putc(),... -> les entrées sont plus associées au clavier / les sorties sont pliés à l'écran (console). Pour plus d'info, voir les liens web
 
''In English'': this chapter talks of the Standart Input/Output with different functions like getc(), putc(),... -> The '''Inputs''' are associated to keyboard / the '''Outputs''' are linked to the screen (see the web link)
 
==== code part ====
'' In French: '' Pour utiliser les instructions décrites ci-dessous, ajouter en début de programme
 
'' In English: '' To use the different functions below, inscribe the next line :
 
'''#include <stdio.h>''' [9]
 
===== Function: GETC(SDTIN) =====
'' IN french : '' cette fonction enregistre dans son buffer a caractère taper au clavier - on peut récupérer cette valeur à l'aide d'un entier
 
'' IN English :'' this function is used to get back a character which can be recorded in a integear variable
 
Here the prototype of the function like we can see it in the stdio.h file : '''int getc(FILE *stream)'''
 
<u>exemple</u>:
'''int''' recup_char;
printf("Ecrire un caractere : ") // affichage d'un msg au user
recup_char = getc('''stdin'''); // récupere le caractère sous un format entier
 
===== Function GETCHAR() =====
'' IN french : '' cette fonction enregistre dans son buffer a caractère taper au clavier - on peut récupérer cette valeur à l'aide d'un entier
 
'' IN English :'' this function is used to get back a character which can be recorded in a integear variable
 
Here the prototype of the function like we can see it in the stdio.h file : '''int getchar()'''
 
<u>exemple</u>:
'''int''' recup_char;
printf("Ecrire un caractere : ") // affichage d'un msg au user
recup_char = getchar(); // récupere le caractère sous un format entier
 
===== Function PUTC(STDOUT) =====
this function is used to place a character in a file or to display this value on the screen.
 
Here the prototype of the function like we can see it in the stdio.h file : '''int putc(int c, FILE *Stream)'''
 
<u>exemple</u>:
'''int''' char_A = 65;
printf("le caractere est : ") // affichage d'un msg au user
putc(char_A, stdout); // affiche la valeur de d'un caractère
 
'''remark''': this function need of two arguments
 
===== Function PUTCHAR() =====
this function is used to place a character in a file or to display this value on the screen.
 
Here the prototype of the function like we can see it in the stdio.h file : '''int putchar(int c)'''
 
<u>exemple</u>:
'''int''' char_A = 65;
printf("le caractere est : ") // affichage d'un msg au user
putchar(char_A); // affiche la valeur de d'un caractère
 
'''remark''': this function need just of one arguments
 
===== Function PRINTF() =====
this function allows to dsiplay on the screen some characters, string, numeric value...
 
Here the prototype of the function like we can see it in the stdio.h file : '''int printf(const char *format, ...)''' to do simple, the first argument corresponds with texte and format indicators, the others arguments are linked to number of the indicators.
 
==== Trick ====
 
=== chapter 6 & 8 (résumé) ===
''In French'': Dans ces chapitres, les sujets traité seront les différentes notions d' '''opérateur'''
 
''In English'': the subjects treated in these chapter concern the '''operateur''' notions
 
==== code part ====
===== Operateur d'affection (=) =====
allocation of variable by a constante or an other variable
 
<u>exemple</u>:
int a, b;
a = 5; // allocation of the value 5 to a
b = a; // allocation of a to B
 
===== Operateur arithmetique (+, -, / , *,...) =====
 
<u>exemple</u>:
int a, b;
a = 5; // allocation of the value 5 to a
b = a; // allocation of a to B
a = a + b; a += b; // new allocation of a by addition / same writting
a = a - b; a -= b; // new allocation of a by subtraction / same writting
a = a * b; a *= b; // new allocation of a by multiplication / same writting
a = a / b; a /= b; // new allocation of a by division / same writting
a = a % b; a %= b; // new allocation of a by modulo / same writting
 
===== Operateur unaire moins (-) =====
to get back a negative number
 
<u>exemple</u>:
int a, b, c;
a = 5; // allocation of the value 5 to a
b = a; // allocation of a to B
c = a - -b; // b become negative
c = a - (-b); // same result that allows
c = a + b; // same result that allows
 
===== Operateur incrementation / decrementation (-- or ++) =====
 
<u>exemple</u>:
int a = 5;
//pre incremntation
++a;
//post incrementation
a++;
//pre decremntation
--a;
//post decrementation
a--;
 
===== Operateur relationnel =====
comparison between two variables, the result is '1' if the test is positive and '0' if the test is negtaive
 
<u>exemple</u>:
int a, b;
// test d'équalité
a == b;
// test de difference
a != b;
// test de supériorité
a > b;
// test de supériorité ou d'égalité
a >= b;
// test d'inférieurité
a < b;
// test d'inférieurité ou d'égalité
a <= b;
 
===== Operateur de conversion =====
change the type of a variable
 
<u>exemple</u>:
int a;
(char)a;
 
===== Operateur "sizeof" =====
'' In French:'' Connaître la taille d'un type qui sera indiqué en octet
 
''In English '': know the size of type (integer, float, double, ect) in byte
 
<u>exemple</u>:
int var_r, var_1;
// détermine la taille d'un entier en octet
sizeof(int);
//détermine la taille de double en octet
sizeof(double);
// détermine la taille d'une variable
var_r = sizeof var_1; or
var_r = sizeof(var_1)
 
Remark: if we don't use a key word C (int, float, ect..) don't need to use the brackets
 
===== Operateur logique "AND(E) - ET(F) => &&" =====
''In French'': compare deux expressions et si les deux sont équivalente, cela retourne un '1' (valeur vraie)
 
''in English'': compare two expressions and if the both are true, return a '1'. See the behavior of this operator with truth table below:
 
{| class="wikitable" style="text-align:center;"
|+ Table de verité pour Operateur &&
|-
! scope="col" | Expression 1
! scope="col" | Expression 2
! scope="col" | E1 && E2 (valeur de retour)
|-
| 0
| 0
| 0
|-
| 0
| 1
| 0
|-
| 1
| 0
| 0
|-
| 1
| 1
| 1
|}
 
<u>Exemple</u>
int A = 1; // Non Null
int B = 2; // Non Null
int C = 0; // Null
int V; // result
V = A && B; // V vaut 1, car les deux champs sont a '1' logiquement
V = A && C; // V vaut 0, car l'un des deux champs est à '0'
 
===== Operateur logique "OR(E) - OU(F) => ||" =====
''In French'' compare deux expressions, et si l'une d'elle est vrai ('1'), les résultats des deux expressions renvoie un '1'(vrai)
 
''In English'': compare two expressions and if one of them is true, return a '1'. See the behavior of this operator with truth table below:
 
{| class="wikitable" style="text-align:center;"
|+ Table de verité pour Operateur OU
|-
! scope="col" | Expression 1
! scope="col" | Expression 2
! scope="col" | E1 OU E2 (valeur de retour)
|-
| 0
| 0
| 0
|-
| 0
| 1
| 1
|-
| 1
| 0
| 1
|-
| 1
| 1
| 1
|}
 
===== Operateur logique "NO(E) - NON(F) => !" =====
''In french'': inverse le résultat d'une expression -> si celle-ci est vraie ('1'), elle devient fausse('0')
 
''In English'': invert the expression result -> if this one is true ('1'), it becomes false ('0')
 
{| class="wikitable" style="text-align:center;"
|+ Table de verité pour Operateur NON (!)
|-
! scope="col" | Expression 1
! scope="col" | !E1 (valeur de retour)
|-
| 0
| 1
|-
| 1
| 0
|}
 
===== Operateur bit à bit =====
 
& (ET / AND) -> exemple : 0101 & 0110 = 0100
| (OU / OR) -> exemple : 0010 & 0110 = 0110
^ (OU EXCLUSIF / XOR) -> exemple : 0100 ^ 1101 = 1001
~ (inverseur) -> exemple : ~0100 = 1011
 
===== Operateur de Décalage =====
 
décalage a droite de x bits >>
(a = 8) >> (b = 2) = a >> b = 8 >> 2 (la valeur de 8 décaler de 2 bit à droite) = 1000 >> 10 = 0010
décalage à gauche de x bit <<
(a = 8) >> (b = 3) = a << b = 8 << 3 (la valeur de 8 décaler de 3 bit à gauche) = 1000 << 11 = 1000000
 
==== Trick ====
'''Warning''': don't mistake this : '=' & '==' => the first symbol correponds at the allocation / the second symbol corresponds at the test between two variables. Same thing concerning the bit to bit operator and the logique operator
 
<u>Exemple</u>
(a = 8) & (b = 1) = a & b = 1000 & 0001 = 0000
(a = 8) && (b = 1) = a && b = 1000 && 0001 = 1
 
For an expression or an operator which retunrs a value no null (different of zero) is considered like TRUE('1'), but if it is opposite, the return value is FALSE('0')
 
Concenring the gap operator : if there is a gap side right, it is equivalent to cut a value at 2^ the gap value
<u>exemple</u>
(a = 8) >> (b = 2) = a >> b = 8 >> 2 = <math> \frac{8}{(2^2)}</math>
 
if there is a gap side left, it is equivalent to multiply a value at 2 ^ the gap value
<u>exemple</u>
(a = 8) << (b = 2) = a << b = 8 << 2 = <math> {8} \cdot {(2^2)}</math>
 
=== chapter 7 (résumé) ===
 
In French: dans ce chapitre, les notions de boucle (for, while,...) - on parle aussi de traitements itératifs
 
''In Englsih'': in this chapter, the concept of loop will be see (EX: For, While, ...) - we can hear also the word "itreration" when we spoke of loop.
 
==== code part ====
===== LOOP FOR =====
 
int i, y;
for(i = 0 [1]; i < y [2]; i++ [3]) // boucle on l'on fait des instruction spécifique à la boucle
{instructions}
or
for(i = 0 [1]; i < y [2]; i++ [3]); // boucle sans instruction -> boucle d'attente
 
''In French'': il y a 3 expressions dans une boucle '''for'''
 
* [1]: "i = 0" -> initialisation de la/les variables de test
* [2]: "i < y" -> à chaque fin de boucle ce test est effectué pour savoir si on peut sortir de la boucle ou non => le test doit être positif sinon on continue dans la boucle -> la valeur retour du test doit être '0' pour sortir et '1' si le test n'est pas positive
* [3]: "i++" -> si le test non positive, on passe à la 3ème expression qui permet de gérer la/les variables
 
''In English'':
 
* [1]: "i = 0" -> the first expression corresponds at the variable's initialisation
* [2]: "i < y" -> the second expression corresponds at the test in end loop - if the test is positive, it goes out of the loop => if test positive, return value = 0 - else return value = 1 and we stay in the loop
* [3]: "i++" -> the third expression allows if the test is not positive to move the variable(s)
 
===== LOOP WHILE =====
 
int i, y;
while(i < y)
{instructions}
 
'''In French''': ici il y a qu'une expression à évaluer. Avant de rentrer dans la boucle, on évalue l'expression : si celle-ci n'est positive la valeur de retour de l'expression est '1' -> on rentre dans la boucle / si l'expression retourne une valeur de '0' -> on ne rentre pas dans la boucle.
 
'''In English''': to enter in the loop, it must that the expression returns the '1' otherwith the expression returns the '0'
 
===== LOOP DO...WHILE =====
int i, y;
do
{instructions}
while(i < y);
 
'''In French''': pour cette instruction on rentre directement dans la boucle et c'est qu'après la dernière instruction que on évalue l'expression : si celle-ci n'est positive la valeur de retour est '1' -> et on continue d'être dans la boucle autrement la valeur de retour est '0' et on sort de la boucle.
 
'''In English''': we go in directly in the loop - after the last instrcution, the expression is estimated - it must that the expression returns the '1' to otherwith the expression returns the '0'
 
==== Trick ====
===== LOOP FOR =====
''In French'': boucle infinie avec l'instruction '''FOR'''
 
''In English'': infinite loop with '''FOR''' instruction
 
for(;;);
or
for(;;)
{instruction}
 
===== LOOP WHILE =====
''In French'': boucle infinie avec l'instruction '''WHILE'''
 
''In English'': infinite loop with '''WHILE''' instruction
 
while(1);
while(1)
{instruction}
== Liens utiles ==
 
=== lien : vidéo (youtube) ===
* [1] [https://www.youtube.com/watch?v=_fZF5SOAS70 configuration debugger pour code blocks]
 
=== liens : documentation PDF ===
=== liens : documentation Site Internet ===
* [1] [http://www.codeblocks.org/home code blocks site]* [2] [http://fr.wikipedia.org/wiki/American_National_Standards_Institute Wiki sur l'ANSI - American National Standart Institute]* [3] [http://fr.wikipedia.org/wiki/Scanf Explication sur le scanf en C]* [4] [http://fr.wikipedia.org/wiki/Lois_de_De_Morgan Explication sur la loi de Morgan pour les équations logique]* [5] [http://www.apprendre-informatique.com/tutorial/programmation/langage-c/mots-cles-du-c/ mot clé en C]* [6] [http://www.table-ascii.com/ table ASCII]* [6a] [https://www.asciitable.com/ table ASCII]* [7] [http://pubs.opengroup.org/onlinepubs/009695399/functions/fprintf.html explication globale sur les functions f/printf...]* [8] [http://melem.developpez.com/tutoriels/langage-c/initiation-langage-c/?page=es infos sur les entrées - Sorties]* [9] [http://pwet.fr/man/linux/fonctions_bibliotheques/stdio listing des fonctions de la librairie stdio.h]* [10] [http://www.linux-france.org/prj/embedded/sdcc/sdcc_course.formatted_io.html les différents indicateurs de format pour la function printf]* [11] [http://www.cplusplus.com/reference/cstdio/printf/ indicateurs/patramètres pour la fonction de printf]* [12] [https://msdn.microsoft.com/fr-fr/library/cc953fe1.aspx type fondamentaux en C++ sur VS2015]* [13] [https://fr.wikibooks.org/wiki/Programmation_C/Types_de_base Type de base]
== Bibliographie ==
952
edits