C: Difference between revisions

From Computernewb Wiki
Jump to navigation Jump to search
(Created page with "C is a language made by Dennis Ritchie in 1972. Unlike alot of languages of today, C is not dynamic. There is no support for things like garbage collection, methods, operator overloading, dynamic types and generics. == Basic Data Types == *bool: 1 byte. despite being a boolean, it can actually store numbers up to 128. *int: 2 or 4 bytes. *float: 4 bytes and supports numbers with 6 decimal places. *double: 8 bytes and supports numbers with 15 decimal places. == Examples...")
(No difference)

Revision as of 18:15, 20 May 2022

C is a language made by Dennis Ritchie in 1972.

Unlike alot of languages of today, C is not dynamic. There is no support for things like garbage collection, methods, operator overloading, dynamic types and generics.

Basic Data Types

  • bool: 1 byte. despite being a boolean, it can actually store numbers up to 128.
  • int: 2 or 4 bytes.
  • float: 4 bytes and supports numbers with 6 decimal places.
  • double: 8 bytes and supports numbers with 15 decimal places.

Examples

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

int increment(int* value){
    return (*value)++;
}

int main(){
    //error: int is not int*
    //int h = 10;
    //increment(h);
    int a = 41;
    //error: int is not int*
    //int* b = 80
    int* b = (int*)malloc(sizeof(int)); //malloc returns a void* so we must cast it into a int*
    *b = 80; //we must dereference it in order to access the value with a *
    increment(&amp;a);
    increment(b);
    printf("variable a: %i\nvariable b: %i\n", a, *b); //a will return 42 and b will return 81
    return 0;
}

You can try it out here

Notes

  • Pointers will not be automatically allocated. You must allocate the variable with malloc() before you can access the variable and it's members.
  • You cannot do arithmetic on variables that aren't the type of int, float, char or double. If you try to perform arithmetic on a char constant, the compiler will throw errors.
  • If you need to access pointers of the base types, deference them with a *
  • C does not support methods. It is common for C libraries to make pseudo-methods with functions and pointers as args. use a & to access the memory address of the object (if it's stack allocated of course)