Podcast
Questions and Answers
What characteristic differentiates integer variables from unsigned variables in C?
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?
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?
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?
Which of the following is a valid reason for using the gcc -Og
flag during compilation?
What is the primary function of the preprocessor directive #include <stdio.h>
in a C program?
What is the primary function of the preprocessor directive #include <stdio.h>
in a C program?
How does C handle character constants differently from other languages, and what underlying principle does it rely on?
How does C handle character constants differently from other languages, and what underlying principle does it rely on?
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?
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?
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?
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?
Considering the rules for identifier naming in C, which of the following identifiers is syntactically invalid?
Considering the rules for identifier naming in C, which of the following identifiers is syntactically invalid?
How does the associativity of the assignment operator in C impact expressions involving multiple assignments?
How does the associativity of the assignment operator in C impact expressions involving multiple assignments?
Given C's type system and implicit type conversions, what outcome would you anticipate when using an incorrect format specifier in a printf
statement?
Given C's type system and implicit type conversions, what outcome would you anticipate when using an incorrect format specifier in a printf
statement?
Considering the nuances of format control strings in printf
, how does using a field width specifier influence the output of a value?
Considering the nuances of format control strings in printf
, how does using a field width specifier influence the output of a value?
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?
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?
Considering the behavior of format specifiers in printf
, which statement accurately describes the impact of the 0
flag when formatting an integer?
Considering the behavior of format specifiers in printf
, which statement accurately describes the impact of the 0
flag when formatting an integer?
What is the consequence of a format string containing more conversion specifiers than there available output items when using the printf
?
What is the consequence of a format string containing more conversion specifiers than there available output items when using the printf
?
If s
is a short
integer, what would be the correct format specifier to use with the scanf
?
If s
is a short
integer, what would be the correct format specifier to use with the scanf
?
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?
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?
Considering the standard streams available in C, how do you redirect error messages?
Considering the standard streams available in C, how do you redirect error messages?
What is the relationship between BCPL and the C program?
What is the relationship between BCPL and the C program?
How do you get the exact memory size of a type or a variable on a particular platform?
How do you get the exact memory size of a type or a variable on a particular platform?
Flashcards
BCPL
BCPL
A language to write system programs such as Operating Systems and Compilers, by Martin Richards in 1967.
B language
B language
An early language to create versions of UNIX OS at Bell Labs by Ken Thompson.
C Language
C Language
Developed by Dennis Ritchie, known as the language for UNIX operating systems development, requires high performance.
#include <stdio.h>
#include <stdio.h>
Signup and view all the flashcards
gcc
gcc
Signup and view all the flashcards
argc
argc
Signup and view all the flashcards
argv
argv
Signup and view all the flashcards
-o [EXECUTABLE_NAME]
-o [EXECUTABLE_NAME]
Signup and view all the flashcards
C's primitive data types
C's primitive data types
Signup and view all the flashcards
Signed integers
Signed integers
Signup and view all the flashcards
Integer type
Integer type
Signup and view all the flashcards
sizeof operator
sizeof operator
Signup and view all the flashcards
Valid identifiers
Valid identifiers
Signup and view all the flashcards
C program
C program
Signup and view all the flashcards
' escape sequence
' escape sequence
Signup and view all the flashcards
" escape sequence
" escape sequence
Signup and view all the flashcards
Conversion specifiers
Conversion specifiers
Signup and view all the flashcards
Format control string in scanf
Format control string in scanf
Signup and view all the flashcards
Format control string in printf
Format control string in printf
Signup and view all the flashcards
stdio.h
stdio.h
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 ashello.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
- If there are no syntax errors, the compiler creates an executable program named
- Run by entering
./a.out
ora.out
% gcc hello.c -o hello
will create an executable program named hello.
Program Arguments
- Program arguments have specific parameters
- 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
- 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
-g
produces debug info, it annotates the assembly sogdb
can find variables and source code-Wall
enables many warning messages thatshould
beon
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 oftype-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 ofsizeof(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
- Valid identifiers;
- 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 keyboardstdout
- The standard output stream is connected to the screenstderr
- 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
orX
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 is
printf("%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.
- If the value exceeds width format still occurs regardless
-
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);
- Where arguments are stored!
- 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 inint *
. - i reads or can read octal, hex or integer for base conversion that are pointer based
*int
or*unit
, it will takeint *
(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.