Linguagem C - Aula 9.1 - Aprenda a criar e usar Funções e Procedimentos em C (2022)
Understanding Functions in Programming
Introduction to Functions
- The speaker emphasizes the importance of understanding functions, particularly for those advancing in programming careers. Mastery of functions is crucial for working with object-oriented programming later on.
Conceptual Foundations of Functions
- The discussion begins with foundational concepts about functions, including parameters and return values. The speaker notes that beginners often struggle to grasp the purpose of functions.
Importance of Modularization
- As programs grow larger (e.g., 100+ lines), modularizing code into functions becomes essential. This approach helps manage complexity and improves code organization.
- Breaking down complex problems into smaller sub-problems allows for easier management and resolution, highlighting the utility of functions as sub-solutions.
Function Definition and Usage
- Functions serve to encapsulate logic within a program, allowing programmers to reuse code without duplication. This leads to better maintenance and comprehension.
- The speaker explains that using functions can simplify complex tasks by combining smaller solutions, reinforcing their role in modular programming.
Creating New Functions
- To define a new function, one must specify a return type, name it according to variable naming rules, and establish input parameters if necessary.
- The speaker discusses built-in or intrinsic functions that programmers can leverage instead of writing everything from scratch, promoting efficiency in coding practices.
Function Structure
- A function consists of three main components: input data (parameters), output data (return value), and a block of commands that execute the desired logic.
- It’s noted that while defining a function is not mandatory to include a return statement, doing so provides clarity on what the function outputs after execution.
Function Creation and Input Parameters
Understanding Function Inputs
- Functions require input parameters, which are the data provided when invoking the function. The definition of these inputs is crucial for proper function execution.
- Functions can have no inputs, a single input, or multiple inputs. For example, the
putsfunction requires one string input, whileprintfcan take several inputs separated by commas.
Example of Function Declaration
- An example is given where a function named
maioris created to compare two numbers and return the larger one. This illustrates how functions can be structured to perform specific tasks.
- The function's output type is defined as
float, indicating that it will return a floating-point number after comparing its two float-type inputs.
Input Variables and Their Types
- The function accepts two float variables:
num1andnum2. These variables must be specified in parentheses during the function declaration.
- When invoking this function, both arguments must be floats; otherwise, an error may occur due to type mismatch.
Logic Within the Function
- Inside the function, a comparison checks if
num1is greater thannum2. If true, it returnsnum1; otherwise, it returnsnum2.
- If both numbers are equal, either could be returned since they hold the same value. This logic ensures that any valid comparison yields a result.
Utilizing Defined Functions
- After defining the function, it remains inactive until called within another part of the program. This separation allows for organized code structure.
- User input is gathered for variables x and y before calling the previously defined function with these values as arguments.
Execution Flow of Function Call
- Upon calling the function with user-provided values (x and y), those values are copied into num1 and num2 respectively within memory.
- The result from executing this comparison logic returns to assign to variable m. Finally, this output is displayed using formatted print statements.
Function Parameters and Data Types in Programming
Understanding Function Logic
- The statement "34 is greater than 45" is evaluated as false, leading to a return value of 45 being assigned to variable M.
- Upon execution, the function prints "greater: 45.00", confirming the expected output based on the logic described.
Importance of Functions
- The instructor emphasizes that while this example is simple, it serves to illustrate fundamental concepts without overwhelming complexity.
- Functions can have multiple parameters; they are not limited to basic data types like float or int but can also include structures.
Parameter Types and Syntax
- Different parameter types can be defined for functions, including user-defined structures alongside primitive types.
- When defining parameters, one must specify both the type and name of each input variable clearly.
Working with Arrays and Vectors
- The syntax for declaring vectors involves specifying the data type followed by an array name within brackets.
- A second parameter indicating the size of the vector is necessary since functions do not inherently know its length when passed as an argument.
Advanced Vector Handling
- Another method involves passing a vector's size directly within brackets during declaration for clarity in function usage.
- An alternative syntax uses pointers (indicated by an asterisk), allowing dynamic memory management for arrays.
Matrix Parameterization
- For matrices, similar principles apply where dimensions must be specified using nested brackets to indicate sizes accurately.
- Each dimension's size must be declared explicitly; failure to do so may lead to errors in matrix manipulation within functions.
Practical Application of Functions with Vectors
- Three distinct functions (Prime 1, Prime 2, Prime 3) demonstrate how vectors are passed as parameters effectively.
Understanding Function Syntax and Variable Scope in Programming
Function Definitions and Vector Manipulation
- The function
imprimi 3is similar toimprimi 1, utilizing a loop to print vector elements based on their indices.
- In both
imprimi 2andimprimi 3, the vector is passed along with its size, demonstrating how functions can manipulate vectors effectively.
- When passing matrices as parameters, the first dimension's size can be omitted, but subsequent dimensions must be specified for clarity.
- A nested loop structure is used to iterate through matrix rows and columns, allowing for organized printing of matrix content.
Variable Scope: Local vs Global
- Variables declared within a function are local and inaccessible outside that function, while global variables can be accessed anywhere in the code.
- The use of global variables increases flexibility but also raises concerns about potential unintended modifications across different functions.
Function Declaration and Prototypes
- Functions must be declared before they are invoked in the main program; this ensures that the compiler recognizes them during execution.
- In larger programs, it may be beneficial to place function definitions after the main section. This requires using function prototypes to inform the compiler of their existence beforehand.
Function Prototypes and Definitions in Programming
Understanding Function Prototypes
- The speaker introduces the concept of function prototypes, explaining that they include the function's type, name, and parameters. The declaration ends with a semicolon without opening braces.
- An example is provided where the function definition spans lines 15 to 20, while its prototype appears before the
mainfunction. This structure allows for clear organization of code.
- The prototype informs the compiler about a function named
maior, which returns a float and takes two float parameters. This enables invocation withinmaineven if the full definition follows later.
- If the prototype is removed, compilation fails due to conflicting types for
maior. The machine cannot recognize it as an invocation without prior knowledge from the prototype.
- Moving the full function definition before
mainresolves compilation issues but deviates from teaching about prototypes. Listing only prototypes can simplify code management when multiple functions are present.
Implementing Function Prototypes
- The speaker demonstrates copying the first line of a function (excluding braces) to create a proper prototype. It emphasizes maintaining consistency between prototype and definition.
- After executing the code successfully with prototypes in place, it confirms that functions can be recognized correctly by their declarations.
Recap of Key Concepts