C Programming Basics

Choose a study mode

Play Quiz
Study Flashcards
Spaced Repetition
Chat to Lesson

Podcast

Play an AI-generated podcast conversation about this lesson
Download our mobile app to listen on the go
Get App

Questions and Answers

What characteristic differentiates integer variables from unsigned variables in C?

  • There is no difference; both store the same type of data.
  • Integer variables can store larger numbers than unsigned variables.
  • Unsigned variables can store negative numbers, while integer variables cannot.
  • Integer variables reserve the leftmost bit for the sign, while unsigned variables use all bits for the value. (correct)

Which of the following statements is correct about the compilation of a C program?

  • The editor is responsible for checking syntax errors in the C program.
  • The linker combines the object code with the libraries to create an executable file. (correct)
  • The preprocessor directly converts the source code into an executable file.
  • The compiler creates an executable file that can be directly loaded into memory and executed.

In C, how does the sizeof operator interact with expressions regarding operator precedence?

  • The `sizeof` operator has the lowest precedence, so expressions are evaluated before `sizeof` is applied.
  • The `sizeof` operator's precedence is the same as assignment, so expressions are evaluated left to right.
  • The `sizeof` operator's precedence is higher than binary operators like +, so parentheses may be needed for correct evaluation. (correct)
  • The `sizeof` operator can only be applied to type names, not expressions.

Which of the following is a valid reason for using the gcc -Og flag during compilation?

<p>To optimize the code for execution time while maintaining interactive debugging capabilities. (B)</p> Signup and view all the answers

What is the primary function of the preprocessor directive #include <stdio.h> in a C program?

<p>It directs the preprocessor to include the contents of the <code>stdio.h</code> header file into the source code. (D)</p> Signup and view all the answers

How does C handle character constants differently from other languages, and what underlying principle does it rely on?

<p>C treats characters as small integers, relying on the ASCII or a similar encoding. (B)</p> Signup and view all the answers

Given C's approach to variable declaration and the compilation process, what is a potential consequence of omitting the declaration of a variable before its use?

<p>The compiler will halt the compilation process and issue an error, preventing the creation of an executable. (A)</p> Signup and view all the answers

In C, how does the declaration of a floating-point constant influence its interpretation by the compiler, particularly in the absence of a specific suffix?

<p>It is interpreted as <code>double</code>, providing a balance between precision and portability. (A)</p> Signup and view all the answers

Considering the rules for identifier naming in C, which of the following identifiers is syntactically invalid?

<p>10timesVariable (C)</p> Signup and view all the answers

How does the associativity of the assignment operator in C impact expressions involving multiple assignments?

<p>Assignments are evaluated from right to left, with each assignment using the result of the assignment to its right. (D)</p> Signup and view all the answers

Given C's type system and implicit type conversions, what outcome would you anticipate when using an incorrect format specifier in a printf statement?

<p>It does not promote or demote; it will output an unexpected result. (A)</p> Signup and view all the answers

Considering the nuances of format control strings in printf, how does using a field width specifier influence the output of a value?

<p>If the formatted value has smaller character spacing, the output will be padded. (A)</p> Signup and view all the answers

Given C output formatting with printf, what is the role of a precision specifier when outputting a floating-point number using the %f conversion specifier?

<p>It specifies the number of digits to display after the decimal point, padding with zeros or rounding as necessary. (B)</p> Signup and view all the answers

Considering the behavior of format specifiers in printf, which statement accurately describes the impact of the 0 flag when formatting an integer?

<p>It will output leading zeros to an integer as long as there are fewer characters than the width. (C)</p> Signup and view all the answers

What is the consequence of a format string containing more conversion specifiers than there available output items when using the printf?

<p>Undefined or garbage output depends on the system. (C)</p> Signup and view all the answers

If s is a short integer, what would be the correct format specifier to use with the scanf?

<p><code>%hd</code> (A)</p> Signup and view all the answers

What happens if you try to match a character in a scanf function; and you're trying to match to a comma, but the next character is a space?

<p>scanf will terminate. (D)</p> Signup and view all the answers

Considering the standard streams available in C, how do you redirect error messages?

<p>You can redirect standard error streams to the display screen. (B)</p> Signup and view all the answers

What is the relationship between BCPL and the C program?

<p>The C program evolved from B, which followed BCPL. (D)</p> Signup and view all the answers

How do you get the exact memory size of a type or a variable on a particular platform?

<p>Call the sizeof operator. (B)</p> Signup and view all the answers

Flashcards

BCPL

A language to write system programs such as Operating Systems and Compilers, by Martin Richards in 1967.

B language

An early language to create versions of UNIX OS at Bell Labs by Ken Thompson.

C Language

Developed by Dennis Ritchie, known as the language for UNIX operating systems development, requires high performance.

#include <stdio.h>

Tells the preprocessor to open a particular file and include its contents as part of the file being compiled.

Signup and view all the flashcards

gcc

A step that builds a program is performed, then calls other programs to assemble the program and to link the program's component parts into an executable program that you can run

Signup and view all the flashcards

argc

Integer that holds the number of arguments passed to the program from the command line, including the name of the program itself.

Signup and view all the flashcards

argv

Array of pointers (or array of C-strings) that contains the actual command-line arguments. Each element corresponds to a command-line argument, with argv[0] being the name of the program itself.

Signup and view all the flashcards

-o [EXECUTABLE_NAME]

A flag to names executable file

Signup and view all the flashcards

C's primitive data types

Basic built-in types: integer, float, char.

Signup and view all the flashcards

Signed integers

Integer variables are signed. The leftmost bit is reserved for the sign.

Signup and view all the flashcards

Integer type

Numeric types that are whole numbers.

Signup and view all the flashcards

sizeof operator

The storage size of the object or type in bytes

Signup and view all the flashcards

Valid identifiers

Can contain letters, digits, and underscores, but must begin with a letter or underscore.

Signup and view all the flashcards

C program

A series of tokens.

Signup and view all the flashcards

' escape sequence

Output the single quote (') character.

Signup and view all the flashcards

" escape sequence

Output the double quote (") character.

Signup and view all the flashcards

Conversion specifiers

Tells what type of data to expect as input, such as %d for integers.

Signup and view all the flashcards

Format control string in scanf

Describe the format of the data to be input.

Signup and view all the flashcards

Format control string in printf

Describe the format of the output

Signup and view all the flashcards

stdio.h

Functions that provide standard routines for input and output in C.

Signup and view all the flashcards

Study Notes

  • These study notes concern C programming basics, structure, data types, and input/output.
  • The notes focus on the fundamentals of C programming
  • Relevant tools and techniques for compiling and executing C programs include:
    • gcc, printf, and scanf

The C Programming Language

  • C evolved from BCPL and B
  • BCPL is designed for writing system programs like Operating Systems and Compilers
    • It was made in 1967 by Martin Richards
  • B creates early versions of UNIX OS at Bell Labs
    • It was created by Ken Thompson
    • It is notable because many features are similar to BCPL
  • C evolved from B at Bell Labs
    • It was created by Dennis Ritchie in 1972
  • C is known as the language for UNIX operating systems development
  • C is used to develop systems that require high performance such as:
    • OS
    • embedded systems
    • real time systems
    • Communication systems

Standardization

  • K&R C
    • Described in "The C Programming Language" by Kernighan and Ritchie in 1978
    • This version became a de facto standard
  • C89/C90
    • ANSI standard X3.159-1989 was completed in 1988 and formally approved in December 1989
    • International standard ISO/IEC 9899:1990
  • C99
    • International standard ISO/IEC 9899:1999
    • It incorporates changes from Amendment 1 (1995)

C's Strengths

  • Efficiency, can run quickly and in limited memory
  • Portability, runs on PCs to supercomputers
  • Power, has a large collection of data types and operators
  • Flexibility, adaptable from embedded systems to commercial data processing
  • Standard library has hundreds of functions for input/output, string handling, and storage allocation
  • Integrates with UNIX

C Program Development

  • C programs go through six phases to be executed:
    • Edit: Writing the code
    • Preprocess: Preparing the code for compilation
    • Compile: Translating the code into object code
    • Link: Combining object code with libraries
    • Load: Loading the executable into memory
    • Execute: Running the program

General Form of a Simple Program

  • Case-sensitive language
  • Includes single-line and multi-line comments
  • Has preprocessor directives
  • Uses a standard library ()
  • Contains a main function with {}
  • Uses printf() for output
  • Considers the multiple lines in one print
  • Recognizes escape character () and escape sequences like:
    • \n, \t, \, "
  • Code Style
    • Indentation

Directives

  • #include tells the preprocessor to open a file
  • include its contents as part of the file being compiled

Compiling and Executing

  • C source code files should end with .c such as hello.c
  • The compiler often used is the "Gnu Compiler Collection" (gcc)
  • Gcc is a widely used Free Software compiler
  • Compile using Unix with gcc hello.c
    • If there are no syntax errors, the compiler creates an executable program named a.out
  • Run by entering ./a.out or a.out
  • % gcc hello.c -o hello will create an executable program named hello.

Program Arguments

  • Program arguments have specific parameters
  1. argc (argument count)
  • This is an integer that holds the number of arguments passed to the program from the command line
  • This includes the name of the program itself
  • If no arguments are passed, argc will at least be 1
  1. argv (argument vector)
  • This is an array of pointers or array of C-strings
  • It contains the actual command-line arguments
  • Each element of argv is a string that corresponds to a command-line argument
  • argv[0] is the name of the program itself

Most Common GCC Flags

  • -o [EXECUTABLE NAME] names the executable file
  • -Ox is for code optimization as follows:
    • -O0 Compiles as fast as possible without optimizing, this is the default option
    • -O1, -O2, -O3 Optimizes for reduced execution time
    • Higher numbers typically indicate more aggressive optimization
    • -Os Optimizes code size instead of execution time
    • -Og Optimizes execution time while trying to not prevent interactive debugging
  • -gproduces debug info, it annotates the assembly so gdb can find variables and source code
  • -Wall enables many warning messages that should be on by default
  • -Werror turns all warnings into errors
  • -std=c99 sets the compiler to use the 1999 version of the C standard
  • It disables some extensions

Datatypes

  • Integer Types
  • Include long, short, and unsigned integers
  • Floating Types
    • Include single, double, and extended precision
  • Char

Primitive Data Types

  • Integer variables are signed by default
  • The leftmost bit is reserved for the sign
  • To declare a variable with no sign bit, use unsigned

Integer Data Types

  • C supports integer and floating, numeric types
  • Integer type values are whole numbers
  • Floating-point type values can also have a fractional part
  • Integer types are divided into signed and unsigned categories

Character Sets

  • A variable of type char can be assigned any single character
    char ch;
    ch = 'a'; // lower-case a
    ch = 'A'; // upper-case A
    ch = '0'; // zero
    ch = ' '; // space
    
  • Character constants are enclosed in single quotes, not double quotes
  • C treats characters as small integers
  • In ASCII, character codes range from 0 to 127
  • The character 'a' has the value 97, 'A' has the value 65, '0' is 48, and ' ' is 32
  • Character constants actually have int type rather than char type

The sizeof Operator

  • sizeof(type-name) provides the number of bytes to store a value of type-name
  • sizeof(char) is always 1
  • For 32-bit systems, sizeof(int) is commonly 4
  • The sizeof operator applies to constants, variables, and expressions
  • Omitting parentheses is possible when applying to expressions like sizeof i instead of sizeof(i)

Variables, Declarations, and Assignments

  • Variables must be declared before they are used
  • Variables can be declared one at a time
    int height;
    float profit;
    
  • Alternatively, several can be declared at the same time
    int height, length, width, volume;
    float profit, loss;
    
  • A variable can be given a value by means of assignment
    height = 8;
    profit = 2150.48f;
    
    • The assigned number is said to be a constant
  • A variable can be used to calculate another variable:
    height = 8;
    length = 12;
    width = 10;
     volume = height * length * width; // volume is now 960
    
  • The right side of an assignment can be a formula (or expression in C terminology) involving constants, variables, and operators.

Identifiers

  • Identifiers are names for variables, functions, macros, and more.
  • Identifiers contain letters, digits, and underscores but must start with a letter or underscore
    • Valid identifiers; times10, get_next_char, _done, pay
    • It's best to avoid identifiers that start with an underscore
  • Examples of illegal identifiers: Invalid Identifiers: 10times, get-next-char, char, struct
  • C is case-sensitive, uppercase and lowercase letters are different in identifiers
    • job, joB, jOb, jOB, Job, JoB, JOb, JOB are all different
  • C places no limit on the maximum length of an identifier.

Assignment Operator

Assume: int c = 3, d = 5, e = 4, f = 6, g = 12; Here are some examples and effects of the short-hand assignment operators.

Operator  | Sample Expression | Explanation | Assigns
- ---------|-------------------|-------------|----------------
+=        | c += 7         | c = c + 7    | 10 to c
- =        | d -= 4         | d = d - 4    | 1 to d
- =        | e *= 5         | e = e * 5    | 20 to e
/=        | f /= 3         | f = f / 3    | 2 to f
%=        | g %= 9         | g = g % 9    | 3 to g

Layout of a C Program

  • A C program is a series of is a stream of Tokens
    • Identifiers
    • Keywords
  • Operators
  • Punctuation
  • Constants
  • String literals

Keywords

  • The following keywords cannot be identifiers or file names and they have special meaning to the compiler:
  • auto, do, goto, signed, unsigned, break, double, if, sizeof, void, case, else, int, static, volatile, char, enum, long, struct, while, const, extern, register, switch, continue, float, return, typedef, default, for, short, union
  • Standard additions to C99 include:
  • _Bool, _Complex, _Imaginary, inline, restrict
  • Additions to C11 include:
    • _Alignas, _Alignof, _Atomic, _Generic, _Noreturn, _Static_assert, _Thread_local

Streams

  • Input and output are performed with sequences of bytes called streams
  • Input operations transfer bytes into main memory from a device like a keyboard, a solid-state drive, or a network connection
  • Output operations transfer bytes from main memory to a device like a computer screen, a printer, a solid-state drive, or a network connection
  • When a program starts, it has access to three streams:
    • stdin - The standard input stream is connected to the keyboard
    • stdout - The standard output stream is connected to the screen
    • stderr - The standard error stream is connected to the screen

Formatting

  • Every printf call contains a format string that describes the output format
  • The format string includes includes conversion specifiers, flags, field widths, precisions, and literal characters
  • Percent Sign (%) form Conversion specifications:
  • Floating Point Values Rounding
  • Columns of numbers Align
  • Right/Left Aligning
  • String Characters Inserting
  • Floating numbers exponential formatting display
  • Show Hex and Octal Numbers
  • Set precision with Fixed Size

Printing Integers

  • An integer is a whole number
  • Integer values are displayed according conversion specifications
  • the % Sign is important to define what number to convert (%)
  • Here are the conversion specifiers and description -d as a signed decimal integer -i as a signed decimal integer. -o is an unsigned octal integer. -u as an unsigned decimal integer -x or X an unsigned hexadecimal integer the digit or range is from 0-9 ,X uses the uppercase letters A-F

Float Formatting

  • Floating-point values have a decimal point
  • They are displayed using conversion specifiers summarized below.
Conversion Specifier | Description
- ------ | -------
`e or E` | Exponential notation.
`f or F` | Fixed-point notation.
`g or G` | f or E based on value's magnitude.
L | long double value is displayed.

Conversion Specifiers (e, E and f)

  • The conversion specifiers e and E display floating-point values in exponential notation as what the computer is equivalent to, scientific notation used in mathematics.
  • The %E, %e and %g conversion specifications perform rounding, but %f does not.
  • The E stands for exponent.
  • Precision always prints to decimal points right but values must be pre-determined for conversion.

printf Function

  • There are some restrictions with functions, format, and output.
    • Compilers often do not check on number of conversion specification formats
    • Too many specifications is printf("%d %d\n", i); often wrong!
    • Or not to specifications isprintf("%d\n", i, j); which can be wrong also!
  • Compilers specifications can get jumbled up in output and be in-accurate

Printing in field width

  • Formatting specification examples: -%2d is decimal output using at least 2 character spaces (Defaults to a padded empty space)
    • If the value exceeds width format still occurs regardless -%8.4f format follows 8 character spaces including decimal separator and pads according to empty space and uses 4 digits only.

Literals

Here is a summary about using Literals in an escape sequence:

Escape sequence          |       Description
    ' (single quote)                Output the single quote (') character.
    " (double quote)                Output the double quote (") character.
    ? (question mark)               Output the question mark (?) character.
    \ (backslash)                Output the backslash (\) character.
    a (alert or bell)                 Cause an audible (bell) or visual alert
    b (backspace)                Move the cursor back one position
    f (new page or form feed)      Move the cursor to the next logical page’s start.
    n (newline)                Move the cursor to the beginning of the next line.
    r (carriage return)             Move the cursor to the beginning of the current line.
    t (horizontal tab)             Move the cursor to the next horizontal tab position.
    v (vertical tab)               Move the cursor to the next vertical tab position.

Formatted Input With scanf

  • Input is done with scanf
  • Every scanf statement has contains the format
    • Where arguments are stored! scanf(format-control-string, other-arguments);
  • A Format needs to be defined or can lead to data loss.

scanf Conversion Specifics

  • Int, Float and long variables.
Integer conversion specifics/pointer variables.
  • Int uses d and can be signed, it reads decimally, it takes in int * .
  • i reads or can read octal, hex or integer for base conversion that are pointer based *int or *unit, it will take int *(integers only)
  • o, takes a pointer to an unsigned integer unit *
  • x, X - Are the other specifications unit , for hexidecimal units will function this way. (unsigned pointer)
  • Specifications need correct declaration of values
Using Short
  • Short, Long long or "ell" needs input modifier and an integer conversion as appropriate. short, long or long long integer is to be input

Confusing printf with scanf

  • Code should reflect the right implementation.
    • It does not mean it should be an error per technicality.
    • It can be an issue due to improper formatting.
Improper Commas and variables or other delimiters not explicitly declared or understood will cause mis-compilation

Important note to variables and operators

  • Short summary on functions within different coding patterns or styles with c coding and can assist in code writing.
  • Operators of different format in types.
  • Functions and general application that can be added to other code!

Studying That Suits You

Use AI to generate personalized quizzes and flashcards to suit your learning preferences.

Quiz Team

Related Documents

Use Quizgecko on...
Browser
Browser