I apologize if its been asked before but my search didn't yield the answers I was looking for.
I have been looking at C++ and I am just starting. I am coming from a C# background but even in that it is more of a hobby than a job so I am still far from being efficient in it.
My question is: In C++ will functions/methods have to be created at the top of the file?
For example:
C++
C#Code:#include "stdafx.h" #include <iostream> // Function to do simple calculation and return the result int Calc(int num1, int num2) { using namespace std; return num1 * num2 + num1; } int main() { using namespace std; // Create and initialize variables int firstNum = 0; int secNum = 0; // Ask user to input numbers and assign values cout << "Please enter first number: "; cin >> firstNum; cout << "Please enter second number: "; cin >> secNum; // Calculate and display result on console cout << "\n\nTotal: " << Calc(firstNum, secNum) << endl; system("Pause"); return 0; }
In C# they can be created at the bottom of the project. While this is a small code block in larger applications it seems like it would make code harder to maintain by having everything added to the top.Code:using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication { class Program { static void Main(string[] args) { // Create and initialize variables int firstNum = 0; int secNum = 0; // Ask user to input numbers and assign values Console.Write("Please enter first number: "); Int32.TryParse(Console.ReadLine(), out firstNum); Console.Write("Please enter second number: "); Int32.TryParse(Console.ReadLine(), out secNum); // Calculate and display result on console Console.WriteLine("\nTotal: {0}", Calc(firstNum, secNum)); Console.Write("\nPress any key to continue..."); Console.ReadKey(); } // Function to do simple calculation and return the result static int Calc(int num1, int num2) { return num1 * num2 + num1; } } }
I have not gotten far on the tutorials yet and it may just be their way of doing it. I tried adding the function to the bottom of the file and it said identifier not found so that is why I wanted to ask people with experience if this is the way it has to be done or if there is a way that functions can be added to the bottom and still be ran.
Thanks in advance.




Reply With Quote