Skip to content

Instantly share code, notes, and snippets.

@conleec
Created June 6, 2016 02:17
Show Gist options
  • Save conleec/3f28ae0c9030378167f891906b670c39 to your computer and use it in GitHub Desktop.
Save conleec/3f28ae0c9030378167f891906b670c39 to your computer and use it in GitHub Desktop.
@conleec
Copy link
Author

conleec commented Jun 6, 2016

Remember the Ternary Operator

int minutesPerPound = isBoneless ? 10 : 15;
In this case, if true then assign 10, else assign 15.
REMEMBER THIS

Global Variables and Static Variables

  • Global variables are defined outside of any functions like so:
#include <stdio.h>
#include <stdlib.h>

// Declare a global variable here
float thisIsGlobal;

void nextFunctionHere {
    return 0;
}
  • Static variables are also defined outside any functions, but are only available within a given file, to limit scope somewhat.
#include <stdio.h>
#include <stdlib.h>

// Declare a static variable here
static float thisIsAStaticVariable;

void nextFunctionHere {
    return 0;
}

Looping Notes

  • break stops execution in the middle of the loop
  • continue skips to the next iteration of the loop (INTERESTING)
    • see page 59 of BNR Objective C Programming 2nd Edition

Example of passing arguments via "reference"

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

void metersToFeetAndInches(double meters, double *ftPtr, double *inPtr) {

    *inPtr = modf(meters * 3.281, ftPtr) * 12.0;

}

int main(int argc, const char * argv[]) {

    double meters = 20.0;
    double feet, inches;

    metersToFeetAndInches(meters, &feet, &inches);
    printf("%.1f meters is equal to %.0f feet and %.2f inches. \n", meters, feet, inches);

    return 0;
}
  • See page 72-73 in BNR Objective C Programming 2nd Edition
  • See page 74 to read about dereferencing NULL IMPORTANT

Structs in C

  • Used when you need a variable to hold many pieces of data
    • Each "chunk" of data is known as a member of the struct
#include <stdio.h>

typedef struct {
    float heightInMeters;
    int weightInKilos;
} Person;

float bodyMassIndex(Person p) {
    return p.weightInKilos / (p.heightInMeters * p.heightInMeters);
}

int main(int argc, const char * argv[]) {

    Person mikey;
    mikey.heightInMeters = 1.7;
    mikey.weightInKilos = 96;

    Person aaron;
    aaron.heightInMeters = 1.97;
    aaron.weightInKilos = 84;

    printf("mikey is %.2f meters tall\n", mikey.heightInMeters);
    printf("mikey weights %d kilograms \n", mikey.weightInKilos);
    printf("mikey has a BMI of %.2f\n", bodyMassIndex(mikey));
    printf("aaron is %.2f meters tall\n",aaron.heightInMeters);
    printf("aaron weighs %d kilograms\n", aaron.weightInKilos);
    printf("aaron has a BMI of %.2f\n", bodyMassIndex(aaron));

    return 0;
}

This is an example of using defining a struct with a typedef as per page 76 in BNR 2nd edition

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment